1

我找不到我的问题的答案,所以我要问一个新的。

我有一个对象,我想在同一解决方案中从另一个类填充它的属性。但是该对象应该只公开只读属性,以便外部调用者无法看到或访问设置器(因为没有设置器)。

从同一解决方案填充内部支持变量的最佳方法是什么?我知道我可以在构造函数中做到这一点,但我希望能够在创建对象后设置变量。

抱歉我的奇怪解释,也许一些代码可以帮助。

这就是我现在正在做的事情:

Public Class ReadonlyObject

    Protected Friend Sub New()
    End Sub

    'Could use this, but don't want to...
    Protected Friend Sub New(foo As String)
    End Sub

    Friend _foo As String

    Public ReadOnly Property Foo As String
        Get
            Return _foo
        End Get
    End Property

End Class

Public Class FillReadonlyObject

    Private Sub DoSomeHeavyWork()
        Dim roObject As New ReadonlyObject

        roObject._foo = "bar"

        'Could use this, but don't want to...want to access properties directly.
        Dim roObject2 As New ReadonlyObject("bar")

    End Sub

End Class

有了这个,ReadonlyObject 的属性被正确地公开为只读,但我担心这是不好的做法。

我见过这样的实现:

Public Class ReadonlyObject

Protected Friend Sub New()
End Sub

Private _foo As String

Public Property Foo As String
    Get
        Return _foo
    End Get
    Friend Set(value As String)
        _foo = value
    End Set
End Property

End Class

Public Class FillReadonlyObject

Private Sub DoSomeHeavyWork()
    Dim roObject As New ReadonlyObject

    roObject.Foo = "bar"
End Sub

End Class

这可行,但使用 setter 公开属性。它不可访问,但它是可见的,我不希望这样:)

所以也许这只是一个装饰性的东西,但我认为告诉调用者(或至少是智能感知)该属性是严格只读的很好。

谢谢,扬

4

1 回答 1

1

如果您想显式声明该属性为只读,但在构造它之后仍有办法设置它,那么您需要做的就是创建自己的 setter 方法,而不是使用自动为您创建的 setter 方法,但财产。例如:

Public Class ReadonlyObject
    Protected Friend Sub New()
    End Sub

    Private _foo As String

    Public ReadOnly Property Foo As String
        Get
            Return _foo
        End Get
    End Property

    Friend Sub SetFoo(value As String)
        _foo = value
    End Sub
End Class

Public Class FillReadonlyObject
    Private Sub DoSomeHeavyWork()
        Dim roObject As New ReadonlyObject
        roObject.SetFoo("bar")
    End Sub
End Class

或者,您可以创建两个属性,如下所示:

Public Class ReadonlyObject
    Protected Friend Sub New()
    End Sub

    Public ReadOnly Property Foo As String
        Get
            Return HiddenFoo
        End Get
    End Property

    Friend Property HiddenFoo As String
End Class

Public Class FillReadonlyObject
    Private Sub DoSomeHeavyWork()
        Dim roObject As New ReadonlyObject
        roObject.HiddenFoo = "bar"
    End Sub
End Class
于 2013-08-15T12:33:03.620 回答