简体   繁体   中英

C# Static instance members for each inherited class

Consider the following example:

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);
    }
}

I want to have a static member in each class keeping track of things in that class only and i want it to behave exactly the same for every class, but with different content. Each static member should only keep track of one single class. I want to be able to get access to the classes' static member by just having an instance of any IPropertyCollection.

Something like this:

    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 

Now this will work with my example code but i don't want to repeat all those lines inside A and B and 50 other classes.

Use a (curiously recurring) generic common base class:

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

Since the base class is generic, a different "version" of its static members will be "generated" for each different type parameter.

Just be careful with evil dogs :-)

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

Static members can't be inherited. They belong to the class they are declared on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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