1

我有这样的课

Public Class Settings

        Private _app_folder As String = ""
        Public Property AppFolder() As String
            Get
                Return _app_folder
            End Get
            Set(ByVal value As String)
                _app_folder = value
            End Set
        End Property [...]

然后在另一个类中,我声明它

_settings = New Settings

我为每个属性设置值

_settings.AppFolder = "test"

但是如何将“_settings.AppFolder”属性编辑为“只读”?

4

5 回答 5

2

如果您想让 AppFolder始终为只读,您可以简单地声明它:

Private _app_folder As String = ""
Public ReadOnly Property AppFolder() As String
    Get
        Return _app_folder
    End Get
End Property [...]

如果您想在子类中使其为只读,那么您只能通过在客户端代码尝试设置它时抛出异常来做到这一点 - 无法删除子类的设置器。

Public Class SubSettings inherits Settings
    Private _app_folder As String = ""
    Public Property AppFolder() As String
        Get
            Return _app_folder
        End Get
        Set(ByVal value As String)
            throw new Exception ("This property cannot be set")
        End Set
    End Property [...]

最后,如果你想在它的初始设置之后使它成为只读:

    Private _app_folder As String = ""
    Private hasBeenSet as Boolean = False;
    Public Property AppFolder() As String
        Get
            Return _app_folder
        End Get
        Set(ByVal value As String)
            If (hasBeenSet)
                throw new Exception ("This property cannot be set")
            Else
                hasBeenSet = true
                _app_folder = value
            EndIf
        End Set
    End Property [...]
于 2012-05-24T15:28:34.463 回答
2

除了 RB 的答案之外,您还可以实现一个接口并在您需要属性的只读行为时使用该接口(而不是类)。

Public Interface IReadonlySettings
    ReadOnly Property AppFolder() As String
End Interface

Public Class Settings
    Implements IReadonlySettings

    Private m_AppFolder As String

    Public Property AppFolder() As String
        Get
            Return m_AppFolder
        End Get
        Set
            m_AppFolder = Value
        End Set
    End Property

    private readonly Property ReadonlyAppFolder() As String implements IReadonlySettings.AppFolder
        Get
            Return m_AppFolder
        End Get
    End Property

End Class
于 2012-05-24T15:41:56.077 回答
2

另一种选择是更改属性 Set 的访问权限 - 它可以与 Get 不同。例如,您可以将属性声明为 Public,但将 Set 声明为受保护。在这种情况下,任何人都可以读取该属性,但只有类本身及其派生类可以写入该属性。将 Set 声明为 Friend 将允许类本身和同一程序集中的任何其他类写入该属性。

于 2012-10-08T13:02:45.380 回答
0

使用ReadOnly关键字

Public ReadOnly Property AppFolder() As String
        Get
            Return _app_folder
        End Get
    End Property 
于 2012-05-24T15:25:17.860 回答
0

如果你确实在谈论继承,那么答案是——你不能。这会破坏继承:您的派生类对象是基类对象。因此,如果您有类Derived并且Base无法使此代码无法编译:

Dim d As Base = New Derived()
d.SomeProperty = SomeValue

这必须有效。

于 2012-05-24T15:27:44.473 回答