从通用基类型中发出非泛型类型

时间:2014-12-02 18:22:14

标签: c# .net generics reflection.emit

我正在尝试从通用父级创建非泛型类。但我总是得到InvalidProgramException。

我的基类:

public interface IServiceType{}
public class ServiceType: IServiceType{}
public class EntityType{}
public class KeyType{}

public class Base<TService,TEntity, TKey>
{
    public Base(TService service)
    {
        Service = service;
    }

    public TService Service { get; set; }
}

类型构造函数:

static Type CreateType(Type serviceType, Type entityType, Type keyType)
{
    var assemblyName = new AssemblyName("AssName");
    var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
    var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainMod");

    var tb = moduleBuilder.DefineType(serviceType.Name.Substring(1)+entityType.Name, TypeAttributes.Public);

    var baseType = typeof (Base<,,>).MakeGenericType(serviceType, entityType, keyType);

    tb.SetParent(baseType);

    var baseCtor = baseType.GetConstructor(new [] {serviceType});
    if (baseCtor == null)
        throw new InvalidOperationException("Base type constuctor not found");

    var constuctor = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] {serviceType});

    var ilgen = constuctor.GetILGenerator();
    ilgen.Emit(OpCodes.Ldarg_0);
    ilgen.Emit(OpCodes.Call, baseCtor);
    ilgen.Emit(OpCodes.Ret);

  return tb.CreateType();
}

当我调用invoke时,我得到了“调用目标引发了异常。”

void Main()
{
    var type = CreateType(typeof(IServiceType), typeof(EntityType), typeof(KeyType));
    var instance = Activator.CreateInstance(type, new ServiceType{});
    instance.Dump();
}

我做错了什么?

1 个答案:

答案 0 :(得分:4)

您需要传递this和第一个参数

var ilgen = constuctor.GetILGenerator();
ilgen.Emit(OpCodes.Ldarg_0); // this
ilgen.Emit(OpCodes.Ldarg_1); // 1st parameter
ilgen.Emit(OpCodes.Call, baseCtor);
ilgen.Emit(OpCodes.Ret);

Protip:始终将生成的IL转储到程序集并使用PEVerify进行检查。