在仅由构造函数调用的私有方法中赋值readonly变量

tom*_*tom 16 c# readonly private-methods

C#编译器给了我以下错误

CS0191:无法分配只读字段(构造函数或变量初始化程序除外)

我是否必须将代码(在我的私有函数中)移动到构造函数中?这听起来很尴尬.

请注意,私有方法仅供构造函数调用.我希望有一些属性可以用来标记相应的方法.

Zai*_*sud 23

尽管其他帖子说的是,实际上有一种(有点不寻常的)方法,并且实际上在方法中赋值:

public class Foo
{
    private readonly string _field;

    public Foo(string field)
    {
        Init(out _field, field);
    }

    private static void Init(out string assignTo, string value)
    {
        assignTo = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里得到的例子.

或者,您也可以从私有方法返回值,并在构造函数中指定它,如下所示:

class Foo
{
    private readonly string _field;

    public Foo()
    {
        _field = GetField();
    }

    private string GetField()
    {
        return "MyFieldInitialization";
    }
}
Run Code Online (Sandbox Code Playgroud)


Ant*_*bry 6

只读字段只能由构造函数分配。您可以做的是使用方法初始化字段:

class Foo
{
    private readonly Bar _bar = InitializeBar();

    private Bar InitializeBar()
    {
        // Add whatever logic you need to obtain a Foo instance.
        return new Bar();
    }
}
Run Code Online (Sandbox Code Playgroud)


Rit*_*ton 4

是的。您是否尝试过使用构造函数链作为使用通用方法的替代方法?

public StuffClass(string a, char b, int c)
{
    _a = a;
    _b = b;
    _c = c;
}

public StuffClass(string a, char b)
   : this(a, b, 2) 
{}
Run Code Online (Sandbox Code Playgroud)