C#,不变性和公共只读字段 [英] C#, immutability and public readonly fields

查看:123
本文介绍了C#,不变性和公共只读字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在很多地方读到公开揭露领域是不是一个好主意,因为如果你以后想改变属性,你将不得不重新编译它使用类的所有代码。



然而,在一成不变的类的情况下,我不明白你为什么会需要更改为属性 - 你不打算添加逻辑的毕竟设置

在这个有什么想法,我失去的东西吗?



之差的例子,对于那些谁更容易阅读的代码除了文本:)

  //使用公共只读字段
公共类元组LT不可改变元组; T1,T2>
{
公共只读T1项目1;
公共只读T2项目2;
公开元组(T1项目1,T2 ITEM2)
{
项目1 = item1的;
项目2 = ITEM2;
}
}
$ B $使用公共属性和私有只读字段
公共类元组LT b //不可改变元组; T1,T2>
{
私人只读T1 _Item1;
私人只读T2 _Item2;
公开元组(T1项目1,T2 ITEM2)
{
_Item1 = item1的;
_Item2 = ITEM2;
}
公共T1项目1 {{返回_Item1; }}
公共T2项目2 {{返回_Item2; }}
}



当然,你可以使用自动属性(公共T1项目1 {获取;私人集;} ),但这只让你同意不变性',而不是'保证不变性'...

解决方案

这是从属性的明显的遗漏,你可以不写这样的:

 公共T2项目2 {搞定;只读集; } 



我甚至不知道只读是用来表示只能在构造函数中设置的最好的词,但是这就是我们坚持用。



这实际上是一个功能,很多人有要求,所以让我们希望它在C#一段时间,很快一个假设的新版本推出。



请参阅的此相关的问题


I have read in many places that exposing fields publicly is not a good idea, because if you later want to change to properties, you will have to recompile all the code which uses your class.

However, in the case of immutable classes, I don't see why you would ever need to change to properties - you're not going to be adding logic to the 'set' after all.

Any thoughts on this, am I missing something?

Example of the difference, for those who read code more easily than text :)

//Immutable Tuple using public readonly fields
public class Tuple<T1,T2>
{
     public readonly T1 Item1;
     public readonly T2 Item2;
     public Tuple(T1 item1, T2 item2)
     {
         Item1 = item1;
         Item2 = item2;
     }
}

//Immutable Tuple using public properties and private readonly fields
public class Tuple<T1,T2>
{
     private readonly T1 _Item1;
     private readonly T2 _Item2;
     public Tuple(T1 item1, T2 item2)
     {
         _Item1 = item1;
         _Item2 = item2;
     }
     public T1 Item1 { get { return _Item1; } }
     public T2 Item2 { get { return _Item2; } } 
}

Of course, you could use auto-properties (public T1 Item1 { get; private set; }), but this only gets you 'agreed immutability' as opposed to 'guaranteed immutability'...

解决方案

It is an obvious omission from properties that you cannot write something like:

     public T2 Item2 { get; readonly set; } 

I'm not even sure readonly is the best word to use to mean "can only be set in the constructor", but that's what we're stuck with.

This is actually a feature that many people have requested, so let's hope that it will be introduced in a hypothetical new version of C# some time soon.

See this related question.

这篇关于C#,不变性和公共只读字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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