使用反射,我尝试从无参数构造函数创建委托,如下所示:
Delegate del = GetMethodInfo( () => System.Activator.CreateInstance( type ) ).CreateDelegate( delType );
static MethodInfo GetMethodInfo( Expression<Func<object>> func )
{
return ((MethodCallExpression)func.Body).Method;
}
但我得到这个例外:
“无法绑定到目标方法,因为其签名或安全透明度与委托类型不兼容。”什么会起作用?
注意创建委托自 .NET 的先前版本以来,至少对于此配置文件已被移动。现在它在 MethodInfo 上。
正如 phoog 指出的那样,构造函数不会“返回”值;它会“返回”值。另外你可以通过以下方式获取有关它的信息ConstructorInfo
并不是MethodInfo
;这意味着您无法直接围绕它创建委托。您必须创建调用构造函数并返回值的代码。例如:
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
...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)