我确信这是一件非常简单的事情,而且我从根本上不了解属性/变量。我想让类具有在输入某些属性值后分配/计算的变量。这不是功课,我只是使用一个简化的例子。
Public Class person
Public Property name As String
Public Property address As String
Public phoneNumber As String
Public Sub getPhoneNumber()
phoneNumber = lookLookThemUpInThePhoneBook
End Sub
End Class
我可能不知道这个人的姓名和地址,但是一旦他们被分配,我想要计算电话号码。
我知道我可以做到
Dim Eddy As New person
Eddy.name = "Ed Wood"
Eddy.address = "123 Sample Road"
Eddy.getPhoneNumber()
Debug.Print(Eddy.phoneNumber)
但是,手动运行程序会非常麻烦,因此我认为必须有一种方法可以主动分配该值。
我希望能够做到这一点
Eddy.name = "Ed Wood"
Eddy.address = "123 Sample Road"
Debug.Print(Eddy.phoneNumber) ' His phone number is just automatically looked up.
答案 0 :(得分:2)
您可以延迟电话号码查找,直到通过在该属性的setter中实现该逻辑来引用phoneNumber属性(如注释中所述)。这是一个例子:
Public ReadOnly Property phoneNumber As String
Get
'Leverage a class level private variable and wrap in an
'If Statement if you only want To look it up once.
Return lookLookThemUpInThePhoneBook()
End Get
End Property
然后,当你objYourPerson.phoneNumber
时,它会为你寻找。
答案 1 :(得分:1)
名称和地址属性都可以尝试在修改后设置电话号码
Public Class Person
Private _name As String = ""
Private _address As String = ""
Private _phoneNumber As String = "not set yet..."
Public Property Name As String
Get
Return _name
End Get
Set(value As String)
_name = value
setPhoneNumber()
End Set
End Property
Public Property Address As String
Get
Return _address
End Get
Set(value As String)
_address = value
setPhoneNumber()
End Set
End Property
Public Property PhoneNumber As String
Get
Return _phoneNumber
End Get
Private Set(value As String)
_phoneNumber = value
End Set
End Property
Public Sub setPhoneNumber()
If Name <> "" AndAlso Address <> "" Then PhoneNumber = lookThemUpInThePhoneBook(Name, Address)
End Sub
Private Function lookThemUpInThePhoneBook(name As String, address As String) As String
Return "123456789" ' search by name and address here
End Function
End Class
用法:
Sub Main()
Dim Eddy As New Person()
Eddy.Name = "Ed Wood"
Console.WriteLine(Eddy.PhoneNumber)
Eddy.Address = "123 Sample Road"
Console.WriteLine(Eddy.PhoneNumber)
Console.ReadLine()
End Sub
输出
尚未设定......
123456789
答案 2 :(得分:0)
Public Class Person
Public Sub New(strname As String, straddress As String)
name = strname
address = straddress
_phoneNumber = LookThemUpInThePhoneBook(strname, straddress)
End Sub
Private Function LookThemUpInThePhoneBook(pName As String, pAddress As String) As String
Dim myPhone As String = ""
'Do work to look up phone number
Return myPhone
End Function
Private _phoneNumber As String
Public ReadOnly Property phoneNumber As String
Get
Return _phoneNumber
End Get
End Property
Private _name As String
Public Property name As String
Get
Return _name
End Get
Set(value As String)
_name = value
End Set
End Property
Private _address As String
Public Property address As String
Get
Return _address
End Get
Set(value As String)
_address = value
End Set
End Property
End Class
然后
Dim Eddy As New Person("Eddy wood", "123 Sample Road")
Debug.Print(Eddy.phoneNumber)