为什么 ImmutableList<T> 是一个 class 而 ImmutableArray<T> 是一个结构?
Why is ImmutableList<T> a class but ImmutableArray<T> a struct?
当您阅读 ImmutableArray and ImmutableList 的文档时,您可以看到:
ImmutableArray<T>
已实现为 struct
ImmutableList<T>
已实现为 class
问题:
您能解释一下为什么这样的设计决定吗?
特别是为什么ImmutableArray<T>
是struct
.
毕竟,System.Array
是 class
那么,为什么 ImmutableArray<T>
不是这样呢?
本文阐明了将 .Net ImmutableArray 设为“结构”而不是 class:
的决定
https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
✔️ CONSIDER defining a struct instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.
❌ AVOID defining a struct unless the type has all of the following
characteristics:
- It logically represents a single value, similar to primitive types (int, double, etc.).
- It has an instance size under 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
In all other cases, you should define your types as classes.
另请参阅:
当您阅读 ImmutableArray and ImmutableList 的文档时,您可以看到:
ImmutableArray<T>
已实现为struct
ImmutableList<T>
已实现为class
问题:
您能解释一下为什么这样的设计决定吗?
特别是为什么ImmutableArray<T>
是struct
.
毕竟,System.Array
是 class
那么,为什么 ImmutableArray<T>
不是这样呢?
本文阐明了将 .Net ImmutableArray 设为“结构”而不是 class:
的决定https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct
✔️ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
❌ AVOID defining a struct unless the type has all of the following characteristics:
- It logically represents a single value, similar to primitive types (int, double, etc.).
- It has an instance size under 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
In all other cases, you should define your types as classes.
另请参阅: