【问题标题】:Is there a way to have a static readonly field in an abstract class to be instantiated in derived classes?有没有办法在派生类中实例化抽象类中的静态只读字段?
【发布时间】: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");
    }
}

【问题讨论】:

  • staticinstance 这两个词本质上是对立的……
  • 您希望 B 和 C 共享一个列表,并且都在它们的静态 ctor 中添加项目吗?还是您希望 B 和 C 拥有 单独的 静态列表?
  • 我希望BC 有不同的静态列表,我不在乎A。 @Blorgbeard
  • 你知道你的代码失败只是因为x没有初始化?这样做:protected static readonly List&lt;string&gt; x = new List&lt;string&gt;();
  • 您可以创建只读属性。

标签: c# inheritance static abstract-class readonly


【解决方案1】:

如果捕捉到异常,则存在 NullReferenceException 的内部异常。尝试初始化成员x

protected static readonly List<string> x = new List<string>();

【讨论】:

    【解决方案2】:

    您不能“实例化”static 字段。 A 无法指定所有派生类都将具有特定的 static 字段或属性。

    即使您通过初始化 A.x 来修复您的 TypeLoadException:

    public abstract class A
    {
        protected static readonly List<string> x = new List<string>();
    }
    

    您可以看到BC 都使用相同的底层列表:

    B b = new B();
    C c = new C();
    c.X.Dump();     // "asdf, qwer, rrrr, tttt"
    

    如果你想让一个类有一个静态属性,你必须给它一个静态属性。它不能从基类继承它。

    【讨论】:

      猜你喜欢
      • 2015-03-23
      • 1970-01-01
      • 2015-04-11
      • 2019-08-31
      • 2017-04-28
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多