我有以下课程:
public class Entity<T> where T : Entity<T> {
public Factory<T> Factory { get; private set; }
public Entity(Factory<T> factory) {
Factory = factory;
}
}
public class Factory<T> { }
public class MyEntity : Entity<MyEntity> {
public MyEntity(Factory<MyEntity> factory) : base(factory) { }
}
我正在尝试使用指定的构造函数动态创建类MyEntity。到目前为止,我有以下代码:
class Program {
static ModuleBuilder _moduleBuilder;
public static ModuleBuilder ModuleBuilder {
get {
if (_moduleBuilder == null) {
AssemblyBuilder asmBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(new AssemblyName("Dynamic"), AssemblyBuilderAccess.Run);
_moduleBuilder = asmBuilder.DefineDynamicModule("MainModule");
}
return _moduleBuilder;
}
}
static void Main(string[] args) {
TypeBuilder typeBuilder = ModuleBuilder.DefineType("MyEntity", TypeAttributes.Public);
Type baseType = typeof(Entity<>).MakeGenericType(typeBuilder);
typeBuilder.SetParent(baseType);
Type factoryType = typeof(Factory<>).MakeGenericType(typeBuilder);
ConstructorBuilder cBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { factoryType });
ILGenerator ctorIL = cBuilder.GetILGenerator();
ctorIL.Emit(OpCodes.Ldarg_0);
ctorIL.Emit(OpCodes.Ldarg_1);
ConstructorInfo c = baseType.GetConstructor(new Type[] { factoryType });
ctorIL.Emit(OpCodes.Call, c);
ctorIL.Emit(OpCodes.Ret);
Type syType = typeBuilder.CreateType();
Console.ReadLine();
}
}
代码失败@ ConstructorInfo c = baseType.GetConstructor(new Type[] { factoryType })
。我收到了NotSupportedException。
有没有办法实现这个目标?我已经被这座石墙挡了三天。任何帮助将不胜感激。
谢谢!
答案 0 :(得分:3)
您需要使用静态TypeBuilder.GetConstructor
方法。我认为这应该有效(未经测试):
ConstructorInfo genCtor = typeof(Entity<>).GetConstructor(new Type[] { typeof(Factory<>).MakeGenericType(typeof(Entity<>).GetGenericArguments()) });
ConstructorInfo c = TypeBuilder.GetConstructor(baseType, genCtor);