仅显示具有只读属性的对象的最佳方法

时间:2013-08-15 12:18:45

标签: vb.net properties accessor

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

我有一个对象,我想在同一个解决方案中从另一个类填充它的属性。但是对象应该只暴露只读属性,这样外部调用者才能看到或访问setter(因为没有setter)。

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

对不起我的奇怪解释,也许一点代码可以帮助。

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

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的属性被正确地公开为readonly但我担心这是不好的做法。

我见过这样的实现:

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公开该属性。它不可访问,但它是可见的,我不希望这样:)

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

谢谢,Jan

1 个答案:

答案 0 :(得分:1)

如果要将属性显式声明为只读属性,但仍然可以在构造之后设置它,那么您需要做的就是创建自己的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