繁体   English   中英

每个继承的类的C#静态实例成员

[英]C# Static instance members for each inherited class

考虑以下示例:

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个类中重复所有这些行。

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

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> { }

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

只要小心邪恶的狗 :-)

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

静态成员不能被继承。 它们属于声明的类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM