在子类中没有任何代码,我希望一个抽象类为每个子类拥有一个静态变量的不同副本。在 C# 中
abstract class ClassA
{
static string theValue;
// just to demonstrate
public string GetValue()
{
return theValue;
}
...
}
class ClassB : ClassA { }
class ClassC : ClassA { }
和(例如):
(new ClassB()).GetValue(); // returns "Banana"
(new ClassC()).GetValue(); // returns "Coconut"
我目前的解决方案是这样的:
abstract class ClassA
{
static Dictionary<Type, string> theValue;
public string GetValue()
{
return theValue[this.GetType()];
}
...
}
虽然这很好用,但我想知道是否有更优雅或内置的方式来做到这一点?
这类似于Can I have different copies of a static variable for each different type of inheriting class,但我无法控制子类