为什么这个DynamicMethod(ldarg.1,newobj,ret)会触发VerificationException?

sta*_*ica 3 c# reflection reflection.emit dynamicmethod verificationexception

我有这个方法,它在一个动态工厂方法中包装一个构造函数:

static Func<TArg1, TResult> ToFactoryMethod<TArg1, TResult>(this ConstructorInfo ctor)
    where TResult : class
{
    var factoryMethod = new DynamicMethod(
         name:           string.Format("_{0:N}", Guid.NewGuid()),
         returnType:     typeof(TResult), 
         parameterTypes: new Type[] { typeof(TArg1) });

    ILGenerator il = factoryMethod.GetILGenerator();
    il.Emit(OpCodes.Ldarg_1);
    il.Emit(OpCodes.Newobj, ctor);
    il.Emit(OpCodes.Ret);

    return (Func<TArg1, TResult>)
         factoryMethod.CreateDelegate(typeof(Func<TArg1, TResult>));
}
Run Code Online (Sandbox Code Playgroud)

但是,下面的代码抛出一个VerificationException.Invoke(…):

ConstructorInfo ctor = typeof(Uri).GetConstructor(new Type[] { typeof(string) });
Func<string, Uri> uriFactory = ctor.ToFactoryMethod<string, Uri>();
Uri uri = uriFactory.Invoke("http://www.example.com");
Run Code Online (Sandbox Code Playgroud)

如果我更换ldarg.1,则不会抛出异常; newobj <ctor>ldnull,所以这个问题必须由这两个IL指令造成的.进一步的实验表明错误在于ldarg.1.(我用ldstr <string>上面的具体例子替换了它.)

有谁看到这些IL指令有什么问题?

Mar*_*Zen 6

此方法是静态的,因此它没有this参数arg0.更改il.Emit(OpCodes.Ldarg_1);通过il.Emit(OpCodes.Ldarg_0);对我工作的罚款.