为什么只读匿名类型在C#中的属性? [英] Why are the properties of anonymous types in C# read-only?

查看:125
本文介绍了为什么只读匿名类型在C#中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,匿名类型的属性是只读的:

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?

推荐答案

在该<一个有趣的文章href=\"http://blogs.msdn.com/sreekarc/archive/2007/04/03/immutable-the-new-anonymous-type.aspx\">here.从那里...

... [B]Ÿ确保成员做
  没有改变,我们确保散列
  常数的寿命
  object.This允许匿名类型
  与喜欢收藏使用
  哈希表,实际上并没有失去
  他们当成员被修改。
  有很多的好处
  immutabilty在于,它极大地
  简化了使用的code
  对象,因为它们只能分配
  值创建时,然后就用
  (想想线程)

... [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)

这篇关于为什么只读匿名类型在C#中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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