我正在尝试从通用父级创建非泛型类。但我总是得到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();
}
我做错了什么?
答案 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进行检查。