2012-10-22 45 views
0

我有一個特定基類型的靜態幫助克隆方法,它不允許我設置基本屬性設置器。爲什麼不能從靜態方法獲得受保護的setter屬性?

public static T Clone<T>(this T source, DomainKey cloneKey) 
    where T : DomainObjectWithKey 
{ 
    T clone = source.Clone(); // binary formatter returns object of type T 
    clone.Key = cloneKey; // this does not compile 
    return (T)clone; 
} 

public class DomainObjectWithKey 
{ 
    public DomainKey Key { get; protected set; } 

另一種解決方案是將克隆方法放入類本身,然後允許我使用受保護的setter。但是,我必須指定從派生對象調用克隆的時候,這似乎毫無意義。

因此,我的問題是,是否由於封裝,我不能從靜態方法調用受保護的setter方法?

替代解決方案的示例但爲什麼我必須指定類型?

category.Clone<Category>(otherCategory.Key); // why do I have to specify <Category> here? 

public class Category : DomainObjectWithKey 
{ 
    public long CategoryId { get { return ((IdDomainKey)Key).Id; } } 

    public Category(long categoryId) 
    { 
     Key = new IdDomainKey(categoryId); 
    } 
} 

解決方案

我結束了有這樣的密鑰可以從派生類的實例來訪問,但對於其允許的靜態輔助方法來設置的setter保護內部的公共屬性屬性。

public class DomainObjectWithKey 
{ 
    public DomainKey Key { get; protected internal set; } 
+1

'protected'意味着它只能從類或派生類中調用。擴展方法只是編譯器的靜態方法,並沒有'protected'訪問。 –

+0

Clone 屬於哪一類? – hatchet

+0

克隆是與DomainObjectWithKey相同的DLL內的靜態輔助方法。 – David

回答

2

protected意味着它是對的DomainObjectWithKey子類中可見。您的Clone方法似乎不在DomainObjectWithKey之外。

也許您在尋找internalinternal允許您從同一個DLL中訪問該成員。

+0

由於我需要DomainObjectWithKey的子類來設置密鑰,因此不需要內部查找。我添加了一個顯示派生類的構造函數的部分。 – David

+1

@DavidLiddle然後使用'protected internal';應該涵蓋兩個基地。 –

+0

受保護的內部做了伎倆,謝謝。 – David

相關問題