VB.NET:具有公共getter和受保护setter的属性

时间:2013-07-10 12:38:32

标签: .net vb.net properties

在VB.NET中有没有办法为getter和属性的setter定义不同的范围?

类似的东西(当然这段代码不起作用):

Public Class MyClass
    Private mMyVar As String
    Public ReadOnly Property MyVar As String
        Get
            Return mMyVar
        End Get
    End Property
    Protected WriteOnly Property MyVar As String
        Set(value As String)
            mMyVar = value
        End Set
    End Property
End Class

我知道我可以通过一个方法来实现这一点,该方法将属性值作为参数并设置私有变量。但我只是好奇是否有更优雅的方式更贴近属性的概念。

1 个答案:

答案 0 :(得分:18)

当然,语法如下:

Public Property MyVar As String
    Get
        Return mMyVar
    End Get
    Protected Set(value As String)
        mMyVar = value
    End Set
End Property