有人可以向我解释 Get 和 Set 属性的概念吗?它只是不适合我。
最佳答案
这不是 vb.net 固有的概念。它是 .net 框架和 oop 的一部分。长话短说,这只是客户使用对象/与对象交互的方式,以迫使他/她遵循特定的使用模式。这是一种在可以实现某些逻辑的层之后读取/设置私有(private)成员/变量值的方法。例如在一个名为 Account 的类的 setter 实现中。假设它有一个名为 Balance 的属性,它是字符串数据类型(为了举例),但只有数值。
Dim acc as New Account("CustID-1234")
acc.Balance = "1234" 'This is valid
acc.Balance = "Ten thousand" 'this is wrong
因此,为了提供对象数据的一致性(在读取/设置时),我们分别使用了 getter 和 setter。
现在上面类的setter可以这样写:
Public Class Account
'...Var dec
Public Property Balance() As String
Get
Return m_iBal.ToString()
Set (value As String)
Dim i As Integer
If Integer.TryParse(value, i) Then
m_Bal = i
Else
'You can throw a nasty error
End If
End Property
End Class
关于vb.net - Visual Basic .Net 中的属性访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1638391/