【问题标题】:Dynamic Type Creation with a Constructor that reference its dependencies使用引用其依赖项的构造函数创建动态类型
【发布时间】:2012-04-22 01:09:10
【问题描述】:

我有以下课程:

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。

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

谢谢!

【问题讨论】:

  • 打电话给 Eric Lippert,Eric Lippert?
  • @JoeTuskan:我认为这里不需要我;这是一个关于反射的直截了当的问题。

标签: c# dynamic reflection reflection.emit


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2017-09-06
    • 2012-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    相关资源
    最近更新 更多