ZetCode

FreeBasic Is 关键字

最后修改日期:2025 年 6 月 16 日

FreeBasic 的 Is 关键字用于比较对象引用。它检查两个对象变量是否引用内存中的同一实例。

基本定义

在 FreeBasic 中,Is 是专门用于对象的比较运算符。如果两个操作数引用同一个对象,则返回 true。

与比较值的相等运算符 (=) 不同,Is 比较的是内存地址。在 FreeBasic 中处理类和对象时,这一点至关重要。

比较简单对象

此示例演示了使用 Is 关键字进行基本对象比较。

is_simple.bas
Type Person
    Dim fname As String
End Type

Dim p1 As Person Ptr = New Person
Dim p2 As Person Ptr = p1

If p1 Is p2 Then
    Print "p1 and p2 reference the same object"
Else
    Print "p1 and p2 reference different objects"
End If

Delete p1

在这里,我们创建一个 Person 对象,并将其引用分配给 p1 和 p2。Is 比较返回 true,因为两个变量都指向同一内存位置。完成后我们必须删除该对象。

比较不同对象

此示例显示了 Is 与不同对象之间的行为。

is_different.bas
Type Car
    Dim model As String
End Type

Dim c1 As Car Ptr = New Car
Dim c2 As Car Ptr = New Car

If c1 Is c2 Then
    Print "Same car object"
Else
    Print "Different car objects"
End If

Delete c1
Delete c2

我们创建了两个独立的 Car 对象。即使它们的内容相同,Is 也会返回 false,因为它们是内存中的不同实例。始终记住删除动态分配的对象。

Is 与 Nothing

Is 关键字可以检查对象引用是否为 null。

is_nothing.bas
Type Book
    Dim title As String
End Type

Dim b As Book Ptr = Nothing

If b Is Nothing Then
    Print "Book reference is null"
Else
    Print "Book reference is valid"
End If

此代码使用 Is Nothing 检查 Book 指针是否为 null。与使用 = 进行对象引用的 null 检查相比,这更安全。该比较正确地识别了 null 引用。

Is 与数组

Is 关键字可以比较数组引用。

is_array.bas
Dim arr1() As Integer = {1, 2, 3}
Dim arr2() As Integer = arr1

If arr1 Is arr2 Then
    Print "Same array reference"
Else
    Print "Different array references"
End If

在这里,我们将 arr1 分配给 arr2,使它们引用同一个数组。Is 比较返回 true。请注意,这会比较引用,而不是数组内容。要进行内容比较,请使用循环。

Is 与函数返回值

此示例使用 Is 来检查函数返回值。

is_function.bas
Function CreateObject(create As Boolean) As Object Ptr
    If create Then
        Return New Object
    Else
        Return Nothing
    End If
End Function

Dim obj As Object Ptr = CreateObject(False)

If obj Is Nothing Then
    Print "No object was created"
Else
    Print "Object created successfully"
End If

该函数返回一个新对象或 null。我们使用 Is 来检查发生了哪种情况。这种模式在创建可能失败的工厂函数中很常见。

Is 与类方法

类方法可以使用 Is 来比较对象实例。

is_method.bas
Type Node
    Dim value As Integer
    
    Function IsSame(other As Node Ptr) As Boolean
        Return @This Is other
    End Function
End Type

Dim n1 As Node Ptr = New Node
Dim n2 As Node Ptr = n1

Print "Same node: "; n1->IsSame(n2)

Delete n1

Node 类包含一个使用 Is 将当前实例与另一个实例进行比较的方法。@ 运算符获取对象的地址。该方法可以正确地识别两个引用何时相等。

Is 与继承

Is 关键字可以与继承的类一起使用。

is_inheritance.bas
Type Animal
    Dim fname As String
End Type

Type Dog Extends Animal
    Dim breed As String
End Type

Dim a As Animal Ptr = New Dog
Dim d As Dog Ptr = New Dog

If a Is d Then
    Print "Same animal instance"
Else
    Print "Different animal instances"
End If

Delete a
Delete d

即使 a 和 d 是不同类型(Animal 和 Dog),Is 也可以比较它们。由于它们是不同的实例,因此此处返回 false。该关键字可以在继承层次结构中工作。

最佳实践

本教程介绍了 FreeBasic 的 Is 关键字,并通过实际示例展示了它在不同场景下的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 FreeBasic 教程