我将程序缩小到:
using System;
using System.Runtime.InteropServices;
abstract class Abstract {
public int a;
}
[StructLayout(LayoutKind.Sequential)]
sealed class TestClass : Abstract {
public int x;
}
sealed class Container {
public TestClass tc;
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("START");
foreach (var field in typeof(Container).GetFields()) {
Console.WriteLine($"{field.Name}: {field.FieldType}");
}
}
}
输出:
START
Unhandled exception. System.TypeLoadException: Could not load type 'TestClass' from assembly 'DEL, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the format is invalid.
at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
at System.Reflection.RtFieldInfo.InitializeFieldType()
at Program.Main(String[] args) in /code/Program.cs:line 27
为什么会出现异常?我可以在子类上使用StructLayout吗?
使用.FieldInfo
进行反射是转移注意力;TestClass
是固有断开的,这可以通过直接使用类型来看出:如果Main()
包含线var tc = new TestClass();
;START";将永远不会打印,因为该方法甚至从未启动。
问题与中相同https://stackoverflow.com/a/39741897/771768和https://stackoverflow.com/a/30968801/771768但如果你在搜索词中包含反射,谷歌就找不到这些。
基类还需要StructLayoutAttribute
:
[StructLayout(LayoutKind.Sequential)]
abstract class Abstract {
public int a;
}