【问题标题】:Why isn't a protected setter property available from a static method?为什么静态方法中没有受保护的 setter 属性?
【发布时间】: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


【解决方案1】:

protected 表示它对DomainObjectWithKey 的子类可见。您的Clone 方法似乎在DomainObjectWithKey 之外。

也许您正在寻找internal? internal 允许您从同一个 DLL 中访问该成员。

【讨论】:

  • 不寻找内部,因为我需要 DomainObjectWithKey 的子类来设置密钥。我添加了一个显示派生类构造函数的部分。
  • @DavidLiddle 然后使用protected internal;这应该涵盖两个基础。
猜你喜欢
  • 2016-03-08
  • 2020-03-31
  • 2013-10-02
  • 2014-12-19
  • 1970-01-01
  • 2016-02-19
  • 2011-09-20
  • 2015-06-28
  • 2013-05-30
相关资源
最近更新 更多