【发布时间】:2010-12-23 00:31:29
【问题描述】:
在子类中没有任何代码,我希望抽象类为每个子类提供不同的静态变量副本。在 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,但我无法控制子类
【问题讨论】:
-
你可以通过破解
Dictionary<Type,...>并调用GetType()来做到这一点,但这太可怕了...... -
对于虚拟/抽象静态成员会很好。见dotnetrocks.com/text/0448/index9.html>(搜索“虚拟静态成员”)
-
为什么不让它不是静态的?
-
BlackTigerX,ClassB 的每个实例的值必须相同 - 但与 ClassC 的值不同
-
使用基类字典中的类型将起作用。感谢您的想法,我不认为这是使其工作的一种方式。
标签: c# inheritance static-variables