问题描述
在这种情况下:
public struct SectorLocator
{
public Surface Side { get; init; } //this is an enum-int
public VerticalPortion Section { get; init; } //this is another enum-int
}
public struct DataLocator
{
public SectorLocator Sector{get; init;}
public MeasureType Measure { get; init; } //this is another enum-int;
}
DataLocator 仍然是值类型吗?或者就像在结构中放入引用类型一样? 当您将 Sector 属性作为参数传递时,它的行为如何?
我没有找到足够清楚的答案。
解决方法
是的,DataLocator
仍然是值类型;完全由 struct
术语定义。值类型可以包含引用,但这不会改变它的行为方式,除了:如果它确实包含,则不允许在 unmanaged
约束中使用它引用(以及一些 API,如 Unsafe
/MemoryMarshal
等可能拒绝与您一起玩)。这实际上与询问 System.Runtime.CompilerServices.RuntimeHelpers.IsReferenceOrContainsReferences<T>()
相同:对于 不 包含引用的值类型,这将返回 false
,对于任何其他场景,将返回 true
。