0

所以我有一个问题,我有一个对象,其中包含彼此松散相关的其他对象。我只希望这个对象成为一种可以读取变量的存储库,但如果使用此对象则不能更改。这是我的起点(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 对象的属性设置为只读,但仅在从此 CompanyVendorContext 对象访问时才可以?

4

4 回答 4

0

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

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

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

CType(context.Company,Company).ID = 1
于 2013-11-13T18:39:16.637 回答
0

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

于 2013-11-13T18:40:16.187 回答
0

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

于 2013-11-13T18:42:14.457 回答
0

当您需要像这样使用只读时,请使用接口。

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
于 2013-11-13T18:52:05.493 回答