【发布时间】:2012-10-22 18:21:06
【问题描述】:
我有一个特定基类型的静态助手克隆方法,它不允许我设置基属性设置器。
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; }
另一种解决方案是将 Clone 方法放在类本身中,这样我就可以使用受保护的 setter。但是,我必须指定何时从派生对象调用 Clone,这似乎毫无意义。
所以我的问题是,是不是因为封装我不能从静态方法调用受保护的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);
}
}
解决方案
我最终拥有了一个公共属性,因此可以从派生类的实例访问 Key,但设置器的内部受保护,允许静态辅助方法设置属性。
public class DomainObjectWithKey
{
public DomainKey Key { get; protected internal set; }
【问题讨论】:
-
protected表示只能从类或派生类内部调用。扩展方法只是编译器的静态方法,没有protected访问权限。 -
Clone
属于哪个类? -
Clone
是与 DomainObjectWithKey 相同的 DLL 中的静态辅助方法。
标签: c# clone static-methods