Why are the properties of anonymous types in C# read-only?

做~自己de王妃 提交于 2019-12-17 03:20:35

问题


In C#, the properties of anonymous types are read-only:

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?


回答1:


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)



来源:https://stackoverflow.com/questions/1089406/why-are-the-properties-of-anonymous-types-in-c-sharp-read-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!