mercredi 10 novembre 2021

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

I narrowed down the program to:

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}");
    }
  }
}

Outputs:

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

Why does the exception happen? Can I use StructLayout on the subclass?





Aucun commentaire:

Enregistrer un commentaire