考虑这段代码:
public enum MyEnum { V1, V2, V3 }
int size = Marshal.SizeOf(typeof(MyEnum));
它抛出异常:
TestConsole.exe 中发生了“System.ArgumentException”类型的未处理异常
附加信息:类型“TestConsole.Program+MyEnum”不能作为非托管结构封送;无法计算出有意义的大小或偏移量。
虽然此代码不会引发异常并size
包含 4:
public enum MyEnum { V1, V2, V3 }
public struct MyStruct
{
public MyEnum en;
}
int size = Marshal.SizeOf(typeof(MyStruct));
谁能解释为什么 .NET 框架无法确定enum
第一个示例代码中的 4 个字节?
更新
Marshal.Sizeof()
在这个通用方法中我失败了:
public bool IoControlReadExact<T>(uint ioControlCode, out T output) where T : struct
{
output = new T();
int outBufferSize = Marshal.SizeOf(typeof(T));
IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize);
if (outBuffer == IntPtr.Zero)
return false;
try
{
uint bytesReturned;
return IoControlRead(ioControlCode, outBuffer, (uint)outBufferSize, out bytesReturned) && ((uint)outBufferSize == bytesReturned);
}
finally
{
output = (T)Marshal.PtrToStructure(outBuffer, typeof(T));
Marshal.FreeHGlobal(outBuffer);
}
}
并且编译器并没有抱怨enum
不是struct
.
解决方案
我可以重构我的通用方法,使其适用于struct
和enum
:
// determine the correct output type:
Type outputType = typeof(T).IsEnum ? Enum.GetUnderlyingType(typeof(T)) : typeof(T);
//...
int outBufferSize = Marshal.SizeOf(outputType);
//...
output = (T)Marshal.PtrToStructure(outBuffer, outputType);