在仅由构造函数调用的私有方法中分配readonly变量的值 [英] assign value of readonly variable in private method called only by constructors

查看:183
本文介绍了在仅由构造函数调用的私有方法中分配readonly变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#编译器给我以下错误

C# compiler gave me the following error

CS0191:不能将只读字段分配给它(在构造函数或变量初始化程序中除外)

CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)

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

Do I have to move the code (in my private function) into the constructor? That sounds awkward.

请注意,专用方法只应由构造函数调用.我希望可以使用某种属性来标记对应的方法.

Note that the private method was intended only to be called by the constructor. I expect that there is some sort of attribute that I can use to mark the method corresponding.

推荐答案

尽管其他帖子在说什么,但实际上一种(有些不同寻常)的方式来执行此操作并实际在其中分配值一种方法:

Despite what the other posts are saying, there is actually a (somewhat unusual) way to do this and actually assign the value in a method:

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;
    }
}

示例来自此处.

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

Alternatively, you can also return the value from a private method and assign it in the constructor as follows:

class Foo
{
    private readonly string _field;

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

    private string GetField()
    {
        return "MyFieldInitialization";
    }
}

这篇关于在仅由构造函数调用的私有方法中分配readonly变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆