c# - 为继承的只读字段赋值?

标签 c# inheritance constructor readonly

所以我有一个有很多 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/

相关文章:

c# - 将 EF LINQ 方法语法转换为查询语法

Android 全局/常用函数

Java调用构造函数

java - 可以从构造函数调用 Private Final 方法吗?

constructor - 为什么 Swift 区分指定初始化器和便利初始化器?

c# - 在 System.Windows.Controls.Image 控件中显示 System.Drawing.Bitmap 对象

c# - 添加带格式的 XML 节点

c# - 即使我在退出菜单时调用了 Cursor.Visible 函数,退出暂停菜单时我的光标仍然可见

javascript - 为什么我不能覆盖类(函数)描述中的方法定义?

c++ - 候选函数不可行:没有已知的从 std::vector 到 std::vector 的转换