我有一個特定基類型的靜態幫助克隆方法,它不允許我設置基本屬性設置器。爲什麼不能從靜態方法獲得受保護的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; }
'protected'意味着它只能從類或派生類中調用。擴展方法只是編譯器的靜態方法,並沒有'protected'訪問。 –
Clone屬於哪一類? –
hatchet
克隆是與DomainObjectWithKey相同的DLL內的靜態輔助方法。 –
David