如何在从构造函数调用的initialize方法中设置只读字段? [英] How do I set a readonly field in an initialize method that gets called from the constructor?
问题描述
我确定我已经在某个地方看到可以通过使用Init()方法上方的属性来执行以下操作了,该属性告诉编译器必须仅从构造函数中调用Init()方法,从而允许要设置的只读字段.我忘记了该属性的名称,但似乎无法在Google上找到它.
I'm sure I've seen somewhere that I can do the following by using an attribute above my Init() method, that tells the compiler that the Init() method must only be called from the constructor, thus allowing the readonly field to be set. I forgot what the attribute is called though, and I can't seem to find it on google.
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;
}
}
推荐答案
Rob's answer is the way to do it, in my book. If you need to initialize multiple fields you can do it using out
parameters:
public class Class
{
private readonly int readonlyField1;
private readonly int readonlyField2;
public Class()
{
Init(out readonlyField1, out readonlyField2);
}
protected virtual void Init(out int field1, out int field2)
{
field1 = 1;
field2 = 2;
}
}
我个人认为这在某些情况下是有道理的,例如当您希望字段为只读
但您也希望能够在派生类(无需通过某些受 protected
构造函数链接的大量参数).但是也许就是我.
Personally I find this makes sense in certain scenarios, such as when you want your fields to be readonly
but you also want to be able to set them differently in a derived class (without having to chain a ton of parameters through some protected
constructor). But maybe that's just me.
这篇关于如何在从构造函数调用的initialize方法中设置只读字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!