c# - 无法在 .NET Core 中创建动态类型

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

我想将 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);
    }
  }

}

它抛出这个:

Unable to load one or more of the requested types. Could not load type 'Child' from assembly '28266a72-fc60-44ac-8e3c-3ba7461c6be4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

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

我做错了什么?

最佳答案

您忘记调用CreateType 。作为documentation说:

Before a type is used, the TypeBuilder.CreateType method must be called. CreateType completes the creation of the type.

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

你应该这样做:

typeBuilder.CreateType();

DefineDefaultConstructor之后。

关于c# - 无法在 .NET Core 中创建动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69602204/

相关文章:

c# - Entity Framework 核心 ObjectContext.Refresh 等效项

c# - 如何从 C# 中的 DLL 获取类型列表?

c# - 为什么这个表达式有效? (C#6.0)

c# - 文档到 .jpg 转换器

c# - 从 Linq 中的数据表中选择不同的行

c# - 从 Class Libary .NET Core 3 中的非 Controller 类访问 ILogger

c# - 方法实现中的正文签名和声明不匹配

reflection - TypeScript - 传递一个类作为参数,以及反射

c# - 在运行时获取继承的对象类型

c# - 这种方法使用安全吗?