简体   繁体   English

Readonly与静态只读澄清

[英]Readonly vs static readonly clarification

I've run into an interesting situation I am trying to understand. 我遇到了一个我想要了解的有趣情况。 I have a readonly struct field in my class. 我班上有一个readonly struct字段。 This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged. 这意味着当我引用它时,它引用一个副本而不是实际副本,因此当我调用一个change方法时,它将使用一个副本,并且原始文件将保持不变。

That is not what I am observing. 这不是我所观察到的。 I only see the expected behavior with a static field. 我只看到静态字段的预期行为。 I expected the behavior for both types. 我期待两种类型的行为。

private struct junk
{
    public int i;

    public void change()
    {
        i += 1;
    }
}

private readonly junk jk;
private static readonly junk jk2;

public Form1()
{
    InitializeComponent();
    jk.change();
    //jk.i is now 1, why? Shouldn't it be changing a copy and not the original jk?
    jk2.change();
    //jk2.i is 0
}

I have a readonly struct field in my class. 我班上有一个readonly struct字段。 This means that when I reference it, it references a copy and not the actual one, so when I call a change method, it will be working with a copy, and the original will remain unchanged. 这意味着当我引用它时,它引用一个副本而不是实际副本,因此当我调用一个更改方法时,它将使用一个副本,并且原始文件将保持不变。

That's not at all what the readonly modifier does. 这根本不是readonly修饰符所做的。 The readonly modifier prevents you from assigning a new value to jk anywhere but in a constructor. readonly修饰符阻止您在构造函数中的任何位置为jk分配新值。 Then, the static modifier allows you to reuse that value independently of the instance of Form1 you are working with. 然后, static修饰符允许您独立于您正在使用的Form1实例重用该值。
That said, neither readonly nor static is making the weird behavior you are describing because that exact behavior cannot be reproduced with the code you've posted. 也就是说, readonlystatic都不会产生你所描述的奇怪行为,因为你所发布的代码无法重现这种确切的行为。

Look at a simpler example in a Console application (which you can try here ): 查看Console应用程序中的一个更简单的示例(您可以在此处尝试):

public class Program
{
    private readonly junk jk;
    private static readonly junk jk2;

    public static void Main()
    {
        var program = new Program();
        program.jk.change();
        Console.WriteLine(program.jk.i); // prints 0

        jk2.change();
        Console.WriteLine(jk2.i); // prints 0
    }
}

public struct junk
{
    public int i;
    public void change()
    {
        i += 1;
    }
}

Then, as @Damien_The_Unbeliever commented, try to avoid mutable struct s as much as you can. 然后,正如@Damien_The_Unbeliever所评论的那样,尽量避免使用可变struct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM