将成员变量声明为只读有哪些好处?它只是为了防止在类的生命周期中有人更改它的值,还是使用这个关键字会导致任何速度或效率的改进?


当前回答

请记住,readonly只应用于值本身,所以如果您使用引用类型,readonly只保护引用不被更改。实例的状态不受只读保护。

其他回答

不要忘记有一种变通方法,可以使用out参数在任何构造函数之外设置只读字段。

有点乱,但是:

private readonly int _someNumber;
private readonly string _someText;

public MyClass(int someNumber) : this(data, null)
{ }

public MyClass(int someNumber, string someText)
{
    Initialise(out _someNumber, someNumber, out _someText, someText);
}

private void Initialise(out int _someNumber, int someNumber, out string _someText, string someText)
{
    //some logic
}

进一步讨论请访问:http://www.adamjamesnaylor.com/2013/01/23/Setting-Readonly-Fields-From-Chained-Constructors.aspx

Readonly可以在声明时初始化,也可以只从构造函数中获取它的值。与const不同,它必须同时进行初始化和声明。 Readonly拥有const所拥有的一切,再加上构造函数初始化

代码https://repl.it/HvRU/1

using System;

class MainClass {
    public static void Main (string[] args) {

        Console.WriteLine(new Test().c);
        Console.WriteLine(new Test("Constructor").c);
        Console.WriteLine(new Test().ChangeC()); //Error A readonly field 
        // `MainClass.Test.c' cannot be assigned to (except in a constructor or a 
        // variable initializer)
    }


    public class Test {
        public readonly string c = "Hello World";
        public Test() {

        }

        public Test(string val) {
          c = val;
        }

        public string ChangeC() {
            c = "Method";
            return c ;
        }
    }
}

添加一个基本方面来回答这个问题:

属性可以通过省略set操作符来表示为只读。所以在大多数情况下,你不需要添加readonly关键字属性:

public int Foo { get; }  // a readonly property

相比之下:字段需要readonly关键字来实现类似的效果:

public readonly int Foo; // a readonly field

因此,将字段标记为只读的一个好处是可以实现与没有设置操作符的属性类似的写保护级别——如果出于某种原因,不需要将字段更改为属性。

用非常实际的术语来说:

如果在dll a中使用const,而dll B引用该const,则该const的值将被编译到dll B中。如果您使用该const的新值重新部署dll a, dll B将仍然使用原始值。

如果在dll a和dll B引用中使用该readonly,则运行时将始终查找该readonly。这意味着如果您使用该只读的新值重新部署dll A, dll B将使用该新值。

令人惊讶的是,只读实际上会导致代码变慢,正如Jon Skeet在测试他的Noda Time库时发现的那样。在本例中,一个在20秒内运行的测试在删除readonly后只花了4秒。

https://codeblog.jonskeet.uk/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields/