【问题标题】:C# Static instance members for each inherited class每个继承类的 C# 静态实例成员
【发布时间】:2011-11-15 20:32:02
【问题描述】:

考虑以下示例:

interface IPropertyCollection
{
    public MethodWrapper GetPropertySetterByName(string name);
    //<<-- I want the implementation from A and B merged into here somehow
}
class A : IPropertyCollection
{
    static PropertyMap properties = new PropertyMap(typeof(A));
    public MethodWrapper GetPropertySetterByName(string name)
    {
        return properties.SomeFunc(name);
    }
}
class B : IPropertyCollection
{
    static PropertyMap properties = new PropertyMap(typeof(B));
    public MethodWrapper GetPropertySetterByName(string name)
    {
        return properties.SomeFunc(name);
    }
}

我希望每个类中都有一个静态成员,仅跟踪该类中的内容,并且我希望它对每个类的行为完全相同,但内容不同。每个静态成员应该只跟踪一个类。我希望能够通过拥有任何 IPropertyCollection 的实例来访问类的静态成员。

类似这样的:

    IPropertyCollection a = new A();
    IPropertyCollection b = new B();
    a.GetPropertySetterByName("asdfsj");  //Should end up in static A.properties 
    b.GetPropertySetterByName("asdfsj");  //Should end up in static B.properties 

现在这将适用于我的示例代码,但我不想在 A 和 B 以及 50 个其他类中重复所有这些行。

【问题讨论】:

  • “静态实例方法”是矛盾的。它要么是静态的,要么是实例的。你真正的意思是你想要一个依赖子类初始化的静态成员,对吧?
  • 在我看来是抽象类的好人选。

标签: c# inheritance static


【解决方案1】:

使用(奇怪地重复出现的)通用通用基类:

abstract class Base<T> : IPropertyCollection where T : Base<T> {
  static PropertyMap properties = new PropertyMap(typeof(T));
  public MethodWrapper GetPropertySetterByName(string name) {
      return properties.SomeFunc(name);
  }
}

class A : Base<A> { }
class B : Base<B> { }

由于基类是通用的,因此将为每个不同的类型参数“生成”其静态成员的不同“版本”。

请小心evil dogs :-)

class Evil : Base<A> { } // will share A's static member...

【讨论】:

【解决方案2】:

Static members 不能被继承。它们属于声明它们的类。

【讨论】:

  • 你知道为什么我收到了关于你的评论的通知吗?我当然没有投反对票,而且我的名字也不是 Downvoter。 “Downvoter”是一种特殊值,可以大量通知所有关注评论流的人吗?
  • @AdamRackis - 不,不是。你可能会收到通知,因为你是唯一的评论者,系统假设我在问你......
猜你喜欢
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 2015-06-10
相关资源
最近更新 更多