【问题标题】:Why is ImmutableList<T> a class but ImmutableArray<T> a struct?为什么 ImmutableList<T> 是一个类,而 ImmutableArray<T> 是一个结构?
【发布时间】:2021-03-26 15:36:54
【问题描述】:

当您阅读ImmutableArrayImmutableList 的文档时,您可以看到:

  • ImmutableArray&lt;T&gt; 已实现为 struct
  • ImmutableList&lt;T&gt; 已实现为 class

问题:

您能解释一下为什么会做出这样的设计决定吗?

特别是,为什么ImmutableArray&lt;T&gt;struct

毕竟System.Arrayclass 那么,为什么ImmutableArray&lt;T&gt; 不是这样呢?

【问题讨论】:

标签: c# immutability design-decisions


【解决方案1】:

这篇文章阐明了将 .Net ImmutableArray 设为“结构”而不是类的决定:

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct

✔️ 考虑定义一个结构而不是一个类,如果 类型很小,通常寿命很短,或者通常嵌入 其他对象。

❌ 避免定义结构,除非该类型具有以下所有条件 特点:

  • 它在逻辑上表示单个值,类似于原始类型(int、double 等)。
  • 实例大小小于 16 字节。
  • 它是不可变的。
  • 不必经常装箱。

在所有其他情况下,您应该将类​​型定义为类。

另见:

【讨论】:

  • 可以为ImmutableList做同样的论据吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 2020-09-19
  • 2015-04-24
  • 2022-06-17
  • 2011-02-15
相关资源
最近更新 更多