为什么 C# 中匿名类型的属性是只读的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1089406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why are the properties of anonymous types in C# read-only?
提问by Roman Starkov
In C#, the properties of anonymous types are read-only:
在 C# 中,匿名类型的属性是只读的:
var person = new { Surname = "Smith", OtherNames = "John" };
person.Surname = "Johnson"; // ERROR: .Surname is read-only
Of course I can declare a real class if I want writable fields or properties, but regardless, what is the reasoning behind this design decision to make the properties read-only?
当然,如果我想要可写的字段或属性,我可以声明一个真正的类,但无论如何,这种使属性只读的设计决策背后的原因是什么?
采纳答案by JP Alioto
Interesting article on that here. From there ...
有趣的文章在这里。从那里 ...
... [B]y ensuring that the members do not change, we ensure that the hash is constant for the lifetime of the object.This allows anonymous types to be used with collections like hashtables, without actually losing them when the members are modified. There are a lot of benefits of immutabilty in that, it drastically simplifies the code that uses the object since they can only be assigned values when created and then just used (think threading)
... [B]y 确保成员不会改变,我们确保散列在对象的生命周期内保持不变。这允许匿名类型与散列表等集合一起使用,而不会在成员被修改时实际丢失它们. 不变性有很多好处,它极大地简化了使用对象的代码,因为它们只能在创建时分配值然后才使用(想想线程)