簡體   English   中英

.Net如何在父對象標記為只讀時使屬性變為只讀

[英].Net How to make properties readonly when parent object is marked as 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對象的屬性設置為只讀,但是只能從此CompanyVendorContext對象進行訪問嗎?

ReadOnly屬性僅使該屬性值ReadOnly只讀; 它不會影響屬性引用的對象的行為。 如果需要創建一個真正的只讀實例,則必須使ICompany不可變,如下所示:

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

當然,這里也需要注意一些事項。 如果Company (實現ICompany的類)是可變的,則沒有什么可以ICompany用戶這樣做:

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

您還需要將ID屬性設置為只讀。

假設您不想將屬性的訪問器設置為私有或受保護,沒有簡單的方法來完成此操作,而無需更改Company類本身以使其所有屬性變為只讀狀態(並且一直在線)。 如果設計不允許您對其進行更改,則可以編寫某種適配器,代理或其他相關的設計模式,這些模式包裝每個屬性的對象,並且不允許設置這些屬性。

當需要使用這樣的只讀方式時,請使用接口。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM