问题描述
请考虑以下示例:
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的实例就可以访问类的静态成员.
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.
类似这样的东西:
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个类中重复所有这些行.
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.
请谨慎使用邪恶的狗:-)
class Evil : Base<A> { } // will share A's static member...
这篇关于每个继承的类的C#静态实例成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!