LayoutKind.Explicit
我对具有属性集的结构有一个小问题。struct
如您所见,我声明了fieldTotal
64 位,fieldFirst
即前 32 个字节和fieldSecond
后 32 个字节。在将fieldfirst
and设置fieldSecond
为之后Int32.MaxValue
,我希望fieldTotal
是Int64.MaxValue
,但实际上并没有发生。为什么是这样?我知道 C# 并不真正支持 C++ 联合,也许它只会在互操作时很好地读取值,但是当我们尝试自己设置值时,它根本就不能很好地处理它?
[StructLayout(LayoutKind.Explicit)]
struct STRUCT {
[FieldOffset(0)]
public Int64 fieldTotal;
[FieldOffset(0)]
public Int32 fieldFirst;
[FieldOffset(32)]
public Int32 fieldSecond;
}
STRUCT str = new STRUCT();
str.fieldFirst = Int32.MaxValue;
str.fieldSecond = Int32.MaxValue;
Console.WriteLine(str.fieldTotal); // <----- I'd expect both these values
Console.WriteLine(Int64.MaxValue); // <----- to be the same.
Console.ReadKey();