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;
}
}
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…