0

我将程序缩小到:

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 吗?

4

1 回答 1

0

倒影带.FieldInfo是一条红鲱鱼;TestClass本质上是损坏的,可以通过直接使用类型来看到:如果Main()包含该行var tc = new TestClass();,则永远不会打印“START”,因为该方法甚至永远不会启动。

问题与https://stackoverflow.com/a/39741897/771768https://stackoverflow.com/a/30968801/771768中的问题相同,但如果您在搜索词中包含反射,Google 将找不到这些问题。

基类StructLayoutAttribute还需要:

[StructLayout(LayoutKind.Sequential)]
abstract class Abstract {
  public int a;
}
于 2021-11-10T17:15:22.363 回答