Reputation:
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.
Upvotes: 1
Views: 2383
Reputation: 56477
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...
Upvotes: 6
Reputation: 499002
Static members can't be inherited. They belong to the class they are declared on.
Upvotes: 4