5

我有一个看起来像这样的通用类型

public class Entity<T> where T : Entity<T>{ ... }

我需要动态构造类型 T。所以它看起来像这样:

public class MyClass : Entity<MyClass>{ ... }

这可以做到吗?

4

1 回答 1

6
AssemblyName assemblyName = new AssemblyName("TestAssembly");
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);

ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name);

TypeBuilder typeBuilder = moduleBuilder.DefineType("MyClass", TypeAttributes.Public);

Type entityType = typeof(Entity<>).MakeGenericType(typeBuilder);

typeBuilder.SetParent(entityType);


Type t = typeBuilder.CreateType();
于 2012-04-05T00:11:33.160 回答