c# - 不可变对象(immutable对象)是好的做法吗?

标签 c# .net immutability

<分区>

我应该尽可能让我的类不可变吗?

我曾经读过 Joshua Bloch 的《Effective Java》一书,他出于各种原因建议使所有业务对象不可变。 (例如线程安全) 这也适用于 C# 吗?

您是否尝试使您的对象不可变,以便在使用它们时减少问题? 还是不值得您创建它们所带来的不便?

最佳答案

一成不变的 Eric Lippert 撰写了一系列关于该主题的博文。第一部分是 here .

引自earlier post他链接到:

ASIDE: Immutable data structures are the way of the future in C#. It is much easier to reason about a data structure if you know that it will never change. Since they cannot be modified, they are automatically threadsafe. Since they cannot be modified, you can maintain a stack of past “snapshots” of the structure, and suddenly undo-redo implementations become trivial. On the down side, they do tend to chew up memory, but hey, that’s what garbage collection was invented for, so don’t sweat it.

关于c# - 不可变对象(immutable对象)是好的做法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763457/

相关文章:

c# Windows 应用程序将文件添加到数据网格控件中

c# - 向 COM 公开索引器之类的属性

c# - 我需要使用 MVVM 导航到另一个包含 WPF 中父对象的子对象的 View

.net - 属性的顺序有什么保证吗?

C# 匿名值类型本质

java - 跳棋游戏板 : store object refs or char values?

c# - 在 Visual Studio 2008 外接程序中,如何判断类的属性实现了哪些接口(interface)?

c# - .NET HTTP GET 与正文

c# - .Net 上缺少 InstallUtil

java - java中字符串混淆