从构造函数创建委托 [英] Create delegate from constructor

查看:25
本文介绍了从构造函数创建委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用反射,我试图从一个像这样的无参数构造函数创建一个委托:

Using reflection, I'm trying to create a delegate from a parameterless constructor like this:

Delegate del = GetMethodInfo( () => System.Activator.CreateInstance( type ) ).CreateDelegate( delType );

static MethodInfo GetMethodInfo( Expression<Func<object>> func )
{
    return ((MethodCallExpression)func.Body).Method;
}

但我得到这个例外:无法绑定到目标方法,因为其签名或安全透明度与委托类型不兼容."什么会起作用?

But I get this exception: "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type." What will work?

请注意 CreateDelegate 已被移动,至少对于此配置文件,自 .NET 的先前版本以来.现在它在 MethodInfo 上.

Note that CreateDelegate was moved, for this profile at least, since the previous version of .NET. Now it's on MethodInfo.

推荐答案

正如 phoog 指出的,构造函数不返回"值;此外,您可以使用 ConstructorInfo 而不是 MethodInfo 获取有关它的信息;这意味着您不能直接围绕它创建委托.您必须创建调用构造函数并返回值的代码.例如:

As phoog points out a constructor doesn't "return" a value; plus you get information about it with ConstructorInfo and not MethodInfo; which means you can't create a delegate around it directly. You have to create code that invokes the constructor and returns the value. For example:

var ctor = type.GetConstructor(Type.EmptyTypes);
if (ctor == null) throw new MissingMethodException("There is no constructor without defined parameters for this object");
DynamicMethod dynamic = new DynamicMethod(string.Empty,
            type,
            Type.EmptyTypes,
            type);
ILGenerator il = dynamic.GetILGenerator();

il.DeclareLocal(type);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ret);

var func = (Func<object>)dynamic.CreateDelegate(typeof(Func<object>));

当然,如果你在编译时不知道类型那么你只能处理Object...

Of course, if you don't know the type at compile time then you can only deal with Object...

这篇关于从构造函数创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆