当编组到类类型的实例时,该类型需要无参数构造函数。否则Marshal.PtrToStructure
会抛出MissingMethodException
。
当编组到包含嵌套类的实例时,他们不需要无参数构造函数。
请参阅下面的示例代码。编组工作正常,输出为1 2 3 4。
但为什么类DummyNested
不需要无参数构造函数?
static void Main(string[] args)
{
var buffer = new byte[10];
buffer[0] = 1;
buffer[1] = 2;
buffer[2] = 3;
buffer[3] = 4;
Dummy dummy;
unsafe
{
fixed(byte* bufferPtr = &buffer[0])
{
dummy = (Dummy)Marshal.PtrToStructure(new IntPtr(bufferPtr), typeof(Dummy));
}
}
Console.WriteLine("{0} {1} {2} {3}", dummy.m_nested1.m_data1, dummy.m_nested1.m_data2, dummy.m_nested2.m_data1, dummy.m_nested2.m_data2);
Console.ReadKey();
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private class DummyNested
{
public byte m_data1;
public byte m_data2;
public DummyNested(byte data1, byte data2)
{
m_data1 = data1;
m_data2 = data2;
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private class Dummy
{
public DummyNested m_nested1;
public DummyNested m_nested2;
private Dummy()
{
// This one is needed to get Marshal.PtrToStructure working, but why not on DummyNested type?
}
public Dummy(DummyNested n1, DummyNested n2)
{
m_nested1 = n1;
m_nested2 = n2;
}
}