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


当前回答

我认为使用只读字段不会带来任何性能上的提升。这只是一个检查,以确保一旦对象完全构造,该字段不能指向一个新值。

然而,“readonly”与其他类型的只读语义非常不同,因为它是由CLR在运行时强制执行的。readonly关键字编译为.initonly,这是CLR可以验证的。

这个关键字的真正优点是生成不可变的数据结构。根据定义,不可变数据结构一旦构造就不能更改。这使得在运行时推断结构的行为变得非常容易。例如,将不可变结构传递给代码的另一个随机部分是没有危险的。他们永远不能改变它,所以你可以根据这个结构可靠地编程。

Robert Pickering写了一篇关于不变性的好处的博客文章。这篇文章可以在这里或archive.org上找到。

其他回答

用非常实际的术语来说:

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

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

不要忘记有一种变通方法,可以使用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 ;
        }
    }
}

readonly关键字用于将成员变量声明为常量,但允许在运行时计算值。这与使用const修饰符声明的常量不同,后者必须在编译时设置其值。使用readonly,您可以在声明中或在字段所属对象的构造函数中设置字段的值。

如果您不想重新编译引用该常量的外部dll(因为它在编译时被替换),也可以使用它。

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

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

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

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

public readonly int Foo; // a readonly field

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