所以我有一个有很多 child 的基类。该基类定义了一些具有默认值的只读属性和变量。这些可能会有所不同,具体取决于 child 。
只读属性/字段允许您更改构造函数内变量的值以及定义,但不能更改其他地方。如果我尝试更改子类构造函数中继承的只读变量的值,我会收到“只读变量只能在构造函数中分配给”错误。为什么会这样,如果没有反射,我该如何解决这个问题?
我的意图:允许用户通过脚本进行扩展,他们只能更改某些字段一次。
最佳答案
原因是您只能在该类的构造函数中分配给readonly 字段。
根据the definition of readonly in the C# Reference (强调我的):
When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
要解决这个问题,您可以在基类中创建一个 protected 构造函数,它接受只读属性的参数。
一个例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Base b = new Child();
Console.WriteLine(b.i);
Console.Read();
}
}
class Base
{
public readonly int i;
public Base()
{
i = 42;
}
protected Base(int newI)
{
i = newI;
}
}
class Child : Base
{
public Child()
: base(43)
{}
}
}
关于c# - 为继承的只读字段赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037546/