【发布时间】:2016-09-12 20:01:47
【问题描述】:
有没有办法让抽象类中的静态只读字段在派生类中实例化?
与其在每个派生类中都有一个static readonly 字段,我更希望它在它们的基类中,并且每个派生类都将实例化自己的唯一字段(该字段在每个派生类中具有不同的值)。
例如这样的:(但它不起作用)
public static void Main()
{
B b = new B(); //TypeInitializationException
var q = b.X;
}
public abstract class A
{
protected static readonly List<string> x;
}
public class B : A
{
public List<string> X
{
get { return x; }
}
static B()
{
x.Add("asdf");
x.Add("qwer");
//or do this instead but it gives an error
//x = new List<string>() { "qwer", "asdf" };
}
}
public class C : A
{
public List<string> X
{
get { return x; }
}
static C()
{
x.Add("rrrr");
x.Add("tttt");
}
}
【问题讨论】:
-
static和instance这两个词本质上是对立的…… -
您希望 B 和 C 共享一个列表,并且都在它们的静态 ctor 中添加项目吗?还是您希望 B 和 C 拥有 单独的 静态列表?
-
我希望
B和C有不同的静态列表,我不在乎A。 @Blorgbeard -
你知道你的代码失败只是因为
x没有初始化?这样做:protected static readonly List<string> x = new List<string>(); -
您可以创建只读属性。
标签: c# inheritance static abstract-class readonly