vb.net - Visual Basic .Net 中的属性访问器

标签 vb.net accessor

有人可以向我解释 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/

相关文章:

properties - 未调用 Swift 中的访问器方法

ios - 如何从另一个对象访问我的 Application Delegate 的窗口访问器方法?

vb.net - 删除目录

c# - 删除具有子目录(非空)的目录

vb.net - 单元测试框架 NUNIT 可以用于集成测试吗?

objective-c - 最佳实践访问器 : @property @synthetise

VB.NET:从第二种形式检索值的最佳方法是什么?

vb.net - Visual Studio 将 1.1 扩展为 1.1000000000000001

java - 在 try-catch block 之后返回 null

c# - 在类中使用访问器是不好的做法吗?