当您阅读ImmutableArray和ImmutableList的文档时,您可以看到:
ImmutableArray<T>
已被实施为struct
ImmutableList<T>
已被实施为class
问题:
你能解释为什么这样的设计决定吗?
特别是,为什么ImmutableArray<T>
是struct
.
毕竟System.Array
是class
这样,为什么不是这样ImmutableArray<T>
呢?
当您阅读ImmutableArray和ImmutableList的文档时,您可以看到:
ImmutableArray<T>
已被实施为struct
ImmutableList<T>
已被实施为class
问题:
你能解释为什么这样的设计决定吗?
特别是,为什么ImmutableArray<T>
是struct
.
毕竟System.Array
是class
这样,为什么不是这样ImmutableArray<T>
呢?
本文阐明了将 .Net ImmutableArray 设为“结构”而不是类的决定:
https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
✔️ 如果类型的实例很小且通常短暂存在或通常嵌入在其他对象中,请考虑定义结构而不是类。
❌ 避免定义结构,除非该类型具有以下所有特征:
- 它在逻辑上表示单个值,类似于原始类型(int、double 等)。
- 它的实例大小小于 16 个字节。
- 它是不可变的。
- 它不必经常装箱。
在所有其他情况下,您应该将您的类型定义为类。
也可以看看: