ZetCode

FreeBasic This 关键字

最后修改于 2025 年 6 月 23 日

FreeBasic 的 This 关键字是指类型方法中当前对象实例的引用。它允许访问对象的成员,并有助于区分局部变量和成员变量。

基本定义

在 FreeBasic 中,当处理用户定义的类型 (UDTs) 时,This 是当前对象实例的隐式引用。它类似于 C++ 中的 this 或 Python 中的 self

This 关键字主要在类型方法中使用,用于访问对象的字段和方法。它有助于解决参数和成员变量之间的命名冲突。

访问成员变量

此示例展示了 This 用于访问成员变量的基本用法。

this_member_access.bas
Type Person
    fname As String
    age As Integer

    Declare Sub SetInfo(fname As String, age As Integer)
    Declare Sub PrintInfo()
End Type

Sub Person.SetInfo(fname As String, age As Integer)
    This.fname = fname
    This.age = age
End Sub

Sub Person.PrintInfo()
    Print "Name: "; This.fname
    Print "Age: "; This.age
End Sub

Dim p As Person
p.SetInfo("John Doe", 35)
p.PrintInfo()

在这里,This 用于区分参数 fname 和成员变量 fname。如果没有 This,赋值将是模糊的。PrintInfo 方法也使用 This 来提高清晰度。

返回当前对象

This 可用于从方法返回当前对象。这允许方法链式调用,即可以在单个表达式中对同一个对象调用多个方法。

this_return_object.bas
Type Counter
    value As Integer
    
    Declare Function Increment() As Counter Ptr
    Declare Sub PrintValue()
End Type

Function Counter.Increment() As Counter Ptr
    This.value += 1
    Return @This
End Function

Sub Counter.PrintValue()
    Print "Value: "; This.value
End Sub

Dim c As Counter
c.Increment()->Increment()->PrintValue()

在此示例中,Increment 方法修改 Counter 类型的 value 字段,并使用 This 返回当前对象的指针。PrintValue 方法使用 This 访问 value 字段,并将其打印到控制台。

传递对象

This 关键字还可以用于将当前对象作为参数传递给其他函数或方法。当你希望从外部函数修改对象时,或者当需要将对象传递给另一个方法进行进一步处理时,这非常有用。

program.bas
Type Point
    x As Integer
    y As Integer

    Declare Sub Move(dx As Integer, dy As Integer)
    Declare Sub Show()
End Type

Sub Point.Move(dx As Integer, dy As Integer)
    This.x += dx
    This.y += dy
End Sub

Sub Point.Show()
    Print "Point: ("; This.x; ", "; This.y; ")"
End Sub


Sub Translate(ByRef p As Point, tx As Integer, ty As Integer)
    p.Move(tx, ty)
End Sub

Dim pt As Point
pt.x = 10
pt.y = 20
Translate(pt, 5, 5)
pt.Show()

此示例演示了将当前对象 pt 传递给 Translate 函数。在 Translate 内部,在 pt 上调用了 Move 方法,该方法修改了其坐标。然后 Show 方法使用这些更新后的坐标打印点。

构造方法中的 This

This 可以在构造方法中用于初始化字段。

this_constructor.bas
Type Rectangle
    width As Integer
    height As Integer

    Declare Constructor(w As Integer, h As Integer)
    Declare Function Area() As Integer
End Type

Constructor Rectangle(w As Integer, h As Integer)
    This.width = w
    This.height = h
End Constructor

Function Rectangle.Area() As Integer
    Return This.width * This.height
End Function

Dim rect As Rectangle = Rectangle(10, 20)
Print "Area: "; rect.Area()

构造方法使用 This 将参数值赋给成员变量。这种模式确保了对象状态的正确初始化。然后 Area 方法使用这些值进行计算。

本教程通过实际示例展示了 FreeBasic This 关键字在不同场景下的用法。

作者

我叫 Jan Bodnar,是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 FreeBasic 教程