.Net如何在父对象标记为只读时使属性只读

时间:2013-11-13 18:33:38

标签: .net vb.net properties scope readonly

所以我遇到一个问题,我有一个对象,其中包含彼此松散相关的其他对象。我只希望这个对象成为一种存储库,可以读取变量,但如果使用这个对象则不会改变。这是我的起点(VB.Net):

Public Class CompanyVendorContext
    Private _company As ICompany
    Private _vendor As IVendor

    Public ReadOnly Property Company As ICompany
        Get
            Return Me._company
        End Get
    End Property

    Public ReadOnly Property Vendor As IVendor
        Get
            Return Me._vendor
        End Get
    End Property

    Public Sub New(ByVal objCompany As ICompany, ByVal objVendor As IVendor)
        Me._company = objCompany
        Me._vendor = objVendor
    End Sub
End Class

现在,恰当地,当我尝试设置对象本身时,就像这样:

Dim context As New CompanyVendorContext(New Company, New Vendor)
context.Company = New Company

它不允许我这样做,这是完美的。但是,当我尝试这样做时:

Dim context As New CompanyVendorContext(New Company, New Vendor)
context.Company.ID = 1

它允许我这样做。我是否可以将Company对象的属性设置为readonly,但仅限于从此CompanyVendorContext对象访问时?

4 个答案:

答案 0 :(得分:0)

ReadOnly属性仅使该属性值为只读;它不会影响属性引用的对象的行为。如果您需要创建一个真正的只读实例,则必须使ICompany不可变,如下所示:

Public Interface ICompany
    ReadOnly Property Id() As Integer
    ...
End Interface

当然,这里也需要注意。如果Company(实现ICompany的类)是可变的,那么没有什么能阻止用户这样做:

CType(context.Company,Company).ID = 1

答案 1 :(得分:0)

您还需要将ID属性设置为readonly。

答案 2 :(得分:0)

假设您不希望将属性的set访问器设置为私有或受保护,那么没有简单的方法可以在不更改Company类本身的情况下将其所有属性设置为只读(并且在线上和之后)。如果设计不允许您更改它,您可以编写某种适配器,代理或其他相关设计模式来包装每个属性的对象,并且不允许设置这些属性。

答案 3 :(得分:0)

当您需要像这样使用readonly时使用界面。

Public Interface ICompanyVendorContext
    ReadOnly Property Company As ICompany
    ReadOnly Property Vendor As IVendor
End Interface

Public Class CompanyVendorContext Implements ICompanyVendorContext

    Private m_Company As ICompany
    Private m_Vendor As IVendor

    Public Property Company As ICompany
        Get
            Return m_AppFolder
        End Get
        Set
            m_AppFolder = Value
        End Set
    End Property

    Public Property Vendor As IVendor
        Get
            Return m_Vendor
        End Get
        Set
            m_Vendor = Value
        End Set
    End Property

    private readonly Property ReadonlyCompany As ICompany implements ICompanyVendorContext.Company
        Get
            Return m_Company
        End Get
    End Property

    private readonly Property ReadonlyVendor As IVendor implements ICompanyVendorContext.Vendor
        Get
            Return m_Vendor
        End Get
    End Property

End Class