什么是不可改变的,只读在C#是什么意思? [英] What does immutable and readonly mean in C#?

查看:255
本文介绍了什么是不可改变的,只读在C#是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是正确的,这是不可能改变一个不可变对象的值?

Is it correct that it is not possible to change the value of an immutable object?

我有一个关于两个场景只读,我想明白了:

I have two scenarios regarding readonly that I want to understand:


  1. 如果我有一个集合并将其标记为只读,如下所示。我还可以叫 _items.Add

  1. What if I have a collection and mark it as readonly, like the following. Can I still call _items.Add?

private readonly ICollection<MyItem> _items;


  • 和还为以下变量中,如果以后我称之为 _metadata.Change 这将改变在一对夫妇的成员变量的内部值的元数据实例。为 _metadata 还是一成不变?

  • And also for the following variable, if later on I call _metadata.Change which will change the internal values of a couple member variable in the Metadata instance. Is _metadata still immutable?

    private readonly Metadata _metadata;
    


  • 有关上述两个变量,我完全理解,我不能直接分配新值,将其初始化和构造之外。

    For both variables above, I totally understand that I can't directly assign new values to them outside of initializer and constructors.

    推荐答案

    我建议你阅读系列的博客通过埃里克利珀职位。第一部分是不变性在C#中第一部分:永恒的种类。内容非常丰富和有益的,一如既往。该系列文章介绍这是什么意思一个变量是的只读一成不变的等详细。

    I suggest you to read the series of blog posts by Eric Lippert. The first part is Immutability in C# Part One: Kinds of Immutability. Very informative and helpful, as always. The series describes what does it mean for a variable to be readonly, immutable etc. in details.

    一般,只读只意味着你不能重新分配构造函数外场。字段本身可以使用,只要它保持相同的实例进行修改。所以,是的,你可以元素添加到存储在集合只读字段。

    Generally, readonly means only that you can't re-assign a field outside the constructor. The field itself can be modified as long as it stays the same instance. So yes, you can add elements to the collection stored in readonly field.

    关于可变性,这是比较复杂的而这取决于一点,你认为什么样的可变性。当内在价值是引用和这些引用本身不发生变化(它指向的实例),你可以说保持不发生变异。但它发生突变的逻辑的。见埃里克帖子中更多的内幕。

    About mutability, this is more complex and it depends a bit what kind of mutability you consider. When Metadata internal values are references and those references itself (the instances it point to) doesn't change, you could say Metadata stays not mutated. But it is mutated logically. See Eric's posts for more insights.

    这篇关于什么是不可改变的,只读在C#是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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