gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:44:30 24 4
gpt4 key购买 nike

考虑以下示例:

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


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

请小心 evil dogs :-)

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

关于c# - 每个继承的类的C#静态实例成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8142768/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com