在仅由构造函数调用的私有方法中分配只读变量的值

发布于 2024-11-26 21:42:00 字数 153 浏览 1 评论 0 原文

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

CS0191: 无法将只读字段分配给(构造函数或变量初始值设定项中除外)

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

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

C# compiler gave me the following error

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

≈。彩虹 2024-12-03 21:42:00

不管其他帖子怎么说,实际上有一种(有点不寻常的)方法可以做到这一点,并在方法中实际分配值:

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

来自 这里

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

class Foo
{
    private readonly string _field;

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

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

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

Example derived from here.

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";
    }
}
つ低調成傷 2024-12-03 21:42:00

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

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

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

Readonly field can only be assigned by the constructor. What you can do is to initialize the field with a method:

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

    private Bar InitializeBar()
    {
        // Add whatever logic you need to obtain a Foo instance.
        return new Bar();
    }
}
一曲琵琶半遮面シ 2024-12-03 21:42:00

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

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

public StuffClass(string a, char b)
   : this(a, b, 2) 
{}

Yes. Have you tried constructor chaining as an alternative to using a common method?

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

public StuffClass(string a, char b)
   : this(a, b, 2) 
{}
北笙凉宸 2024-12-03 21:42:00

readonly 成员只能在类级别或其构造函数中分配。这就是使用readonly关键字的好处。

class Foo
{
    private readonly Foo _foo = new Foo(); // Valid

    public Foo()
    {
        _foo = new Foo(); // Valid
    }

    private void SomeMethod()
    {
        _foo = new Foo(); // Not valid
    }
}

当使用“除了 string 类”的类时,您可以使用 readonly 来替代 const 关键字,因为编译器不允许您将 const 分配给类。

The readonly members can only assigned in the class level or on its constructor. that is the benefit from using the readonly keyword.

class Foo
{
    private readonly Foo _foo = new Foo(); // Valid

    public Foo()
    {
        _foo = new Foo(); // Valid
    }

    private void SomeMethod()
    {
        _foo = new Foo(); // Not valid
    }
}

You can use readonly as alternative to the const keyword when using classes "other that the string class", because the compiler will not allow you to assign a const to a classes.

洋洋洒洒 2024-12-03 21:42:00

如果你想修改它,你不应该首先将其设置为只读。一旦变量是只读的,您只能在构造函数中或在声明时修改它,如错误所示

根据 MSDN

readonly 关键字是可以在字段上使用的修饰符。当字段声明包含 readonly 修饰符时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中进行。

If you want to modify it you should not make it read only in the first place. Once a variable is read only you can modify it only in constructor or at declaration time as error suggests

According to MSDN

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

花之痕靓丽 2024-12-03 21:42:00

您可以将“{ get; private set; }”粘贴到只读声明中的每个等号前面,以实现几乎相同的效果(属性现在可以在类中的任何位置设置,而不仅仅是在构造函数中,但至少在外部不可更改班级)。对于值类型来说这是严格正确的,但对于只读可能具有优势的引用类型则不然。

class Foo
{
    // public readonly MyInt = 30;
    public int MyInt { get; private set; } = 30;
}

You can literally paste "{ get; private set; }" in front of each equals sign in your readonly declarations to achieve almost the same thing (property can now be set in anywhere in class not just in constructor but at least its not changeable outside class). This is strictly true for value types but not reference types in which readonly might have an advantage.

class Foo
{
    // public readonly MyInt = 30;
    public int MyInt { get; private set; } = 30;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文