【问题标题】:Cannot create dynamic type in .NET Core无法在 .NET Core 中创建动态类型
【发布时间】:2021-10-17 07:30:20
【问题描述】:

我想将Child 作为动态类型添加到动态程序集中:

public abstract class Parent { }       // I want to define this statically

public class Child : Parent {          // I want to define this dynamically
  private Child() : base() { }
}

我关注了this的例子。

我添加了 nuget 包 System.Reflection.Emit (v 4.7.0)。

然后这样写:

using System;
using System.Reflection;
using System.Reflection.Emit;

public abstract class Base { }

public class Program {

  public static void Main() {

    // define dynamic assembly
    var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
    var moduleBuilder = assemblyBuilder.DefineDynamicModule(Guid.NewGuid().ToString());

    // define dynamic type
    var typeName = "Child";
    var typeBuilder = moduleBuilder.DefineType(
      typeName,
      TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
      typeof(Base));
    typeBuilder.DefineDefaultConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
    //typeBuilder.CreateType();   // this was missing - see accepted answer below

    // test it
    try {
      typeBuilder.Assembly.GetTypes();                 // <--- throws
    }
    catch (ReflectionTypeLoadException exception) {
      Console.WriteLine(exception.Message);
    }
  }

}

它抛出这个:

无法加载一种或多种请求的类型。 无法从程序集“28266a72-fc60-44ac-8e3c-3ba7461c6be4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null”加载类型“Child”。

这对我来说在单元测试项目中失败了。在dotnetfiddle 上也失败了。

我做错了什么?

【问题讨论】:

    标签: c# .net-core reflection .net-5 reflection.emit


    【解决方案1】:

    你忘了打电话给CreateType。正如documentation 所说:

    在使用类型之前,必须调用TypeBuilder.CreateType 方法。 CreateType 完成类型的创建。

    您可能不需要使用它为任何东西返回的Type 对象,但您仍然需要这样做。毕竟加载类型算作“使用类型”。

    你应该这样做:

    typeBuilder.CreateType();
    

    在你DefineDefaultConstructor之后。

    【讨论】:

    • 现在可以使用了...感谢您的关注!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2018-06-15
    • 1970-01-01
    • 2023-01-24
    • 2011-12-05
    • 2013-04-09
    相关资源
    最近更新 更多