gpt4 book ai didi

c# - 使用引用其依赖项的构造函数创建动态类型

转载 作者:太空狗 更新时间:2023-10-29 17:57:29 24 4
gpt4 key购买 nike

我有以下类(class):

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。

有什么办法可以实现吗?我已经被这个问题困扰了三天。任何帮助将不胜感激。

谢谢!

最佳答案

您需要使用静态 TypeBuilder.GetConstructor方法。我认为这应该有效(未经测试):

ConstructorInfo genCtor = typeof(Entity<>).GetConstructor(new Type[] { typeof(Factory<>).MakeGenericType(typeof(Entity<>).GetGenericArguments()) }); 
ConstructorInfo c = TypeBuilder.GetConstructor(baseType, genCtor);

关于c# - 使用引用其依赖项的构造函数创建动态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10076969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com