Effective C#阅读笔记-6Prefer Immutable Atomic Value Types不可变值类型

Prefer Immutable Atomic Value Types不可变值类型:一旦创建,将不会变化(constant),不能改变object内部状态。

基于不可变值类型创建的上层的模块将会更加的健壮,可靠性也会更加的有保证,由于不可变值类型对象在创创建安之后,内部状态就不能改变,这样就省去了很多状态检查的代码,在多线程环境下也不会出现状态不一致的情况。

对于不可变值类型有以下的好处:

1.多线程安全:If the internal state cannot change, there is no chance for different threads to see inconsistent views of the data. Immutable types can be exported from your objects safely.

2.很适合hash类型的集合:The caller cannot modify the internal state of your objects. Immutable types work better in hash-based collections. The value returned byObject.GetHashCode() must be an instance invariant ; that's always true for immutable types.

实例化不可变值类型对象或者是创建不可值类型对象通常有三种方法

1.创建适当的构造函数,这个是比较简单通常的方法

2.使用工厂方法,静态方法。Factories make it easier to create common values. The .NET FrameworkColor type follows this strategy to initialize system colors. The static methodsColor.FromKnownColor() and Color.FromName() return a copy of a color value that represents the current value for a given system color.

3.创建一个可变的同步类(mutable companion class )来创建一个不可变的对象,这种情况特别适合需要多步才能完成创建的情况,(string 和StringBuiler类就是一个很好的例子)The .NET string class follows this strategy with theSystem.Text.StringBuilder class. You use the StringBuilder class to create a string using multiple operations. After performing all the operations necessary to build the string, you retrieve the immutable string from theStringBuilder

4。Immutable types are simpler to code and easier to maintain. Don't blindly createget and set accessors for every property in your type. Your first choice for types that store data should be immutable, atomic value types. You easily can build more complicated structures from these entities.不要盲目的创建get set属性访问,对于数据存储首选的的不可变的源自操作的值类型对象,基于这些对象你能快速的构建更复杂的对象


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值