Considerate questo codice:Marshal.SizeOf getta ArgumentException su enumerazioni
public enum MyEnum { V1, V2, V3 }
int size = Marshal.SizeOf(typeof(MyEnum));
si genera l'eccezione:
un'eccezione non gestita di tipo 'System.ArgumentException' si è verificato in TestConsole.exe
Ulteriori informazioni: digitare "TestConsole.Program + MyEnum" non può essere sottoposto a marshalling come una struttura non gestita; nessuna dimensione significativa o offset può essere calcolato .
Anche se questo codice non un'eccezione e size
contiene 4:
public enum MyEnum { V1, V2, V3 }
public struct MyStruct
{
public MyEnum en;
}
int size = Marshal.SizeOf(typeof(MyStruct));
Qualcuno può spiegare perché il framework .NET non riesce a capire che il enum
è di 4 byte nel primo campione codice?
UPDATE
Marshal.Sizeof()
fallito su di me in questo metodo generico:
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);
}
}
e il compilatore non si lamentava enum
non essere un struct
.
SOLUZIONE
potevo refactoring il mio metodo generico per farlo funzionare sia per struct
e 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);
[questo] (http://stackoverflow.com/questions/4219413/c-sharp-sizeofenum-alternative-to-workaro-resharper-false-error) non spiega il motivo, ma offre una soluzione alternativa. –
Al contrario, è possibile creare un tipo di puntatore a 'MyEnum', con codice non sicuro, che usa il tipo' MyEnum * '. –