我确定我已经在某处找到了我可以通过使用我的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)