从构造函数创建委托 [英] Create delegate from constructor
问题描述
使用反射,我试图从像这样的无参数构造函数中创建一个委托:
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 。现在它在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>));
当然,如果您在编译时不知道类型,则只能处理对象
...
Of course, if you don't know the type at compile time then you can only deal with Object
...
这篇关于从构造函数创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!