繁体   English   中英

RtFieldInfo.FieldType 导致 System.TypeLoadException:无法从程序集“A...”加载类型“SubClass”,因为格式无效

[英]RtFieldInfo.FieldType causes System.TypeLoadException: Could not load type 'SubClass' from assembly 'A...' because the format is invalid

我将程序缩小到:

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本身就被破坏了,直接使用类型可以看出: If Main() contains the line 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM