小编Ben*_*son的帖子

如何在从构造函数调用的initialize方法中设置只读字段?

我确定我已经在某处找到了我可以通过使用我的Init()方法之上的属性来执行以下操作,该方法告诉编译器必须只从构造函数调用Init()方法,从而允许readonly字段被设定.我忘记了该属性的调用,但我似乎无法在谷歌上找到它.

public class Class
{
    private readonly int readonlyField;

    public Class()
    {
        Init();
    }

    // Attribute here that tells the compiler that this method must be called only from a constructor
    private void Init()
    {
        readonlyField = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# constructor readonly

36
推荐指数
5
解决办法
2万
查看次数

标签 统计

c# ×1

constructor ×1

readonly ×1