gpt4 book ai didi

.net - 从 MethodInfo 构建一个委托(delegate)?

转载 作者:行者123 更新时间:2023-12-03 08:49:12 25 4
gpt4 key购买 nike

在谷歌搜索并登陆 SO 并阅读 this other question 之后

Is it possible to build a correct Delegate from a MethodInfo if you didn't know the number or types of parameters at compile time?



更多信息:不使用 Reflection.Emit 或 type builder 可以优雅地完成吗?

这对我来说有点可惜,因为 Delegate.CreateDelegate 要求我将正确的 Delegate 类型指定为第一个参数,否则它会引发异常或调用不正确的方法。

我正在制造一些忍者装备,这将有很大帮助......谢谢!

这是一个通用的解决方案:
/// <summary>
/// Builds a Delegate instance from the supplied MethodInfo object and a target to invoke against.
/// </summary>
public static Delegate ToDelegate(MethodInfo mi, object target)
{
if (mi == null) throw new ArgumentNullException("mi");

Type delegateType;

var typeArgs = mi.GetParameters()
.Select(p => p.ParameterType)
.ToList();

// builds a delegate type
if (mi.ReturnType == typeof(void)) {
delegateType = Expression.GetActionType(typeArgs.ToArray());

} else {
typeArgs.Add(mi.ReturnType);
delegateType = Expression.GetFuncType(typeArgs.ToArray());
}

// creates a binded delegate if target is supplied
var result = (target == null)
? Delegate.CreateDelegate(delegateType, mi)
: Delegate.CreateDelegate(delegateType, target, mi);

return result;
}

备注 :我正在构建一个 Silverlight 应用程序,它将替换一个多年前构建的 javascript 应用程序,在该应用程序中,我有多个 Javascript 接口(interface)调用相同的 Silverlight [ScriptableMember] 方法。

需要支持所有这些遗留 JS 接口(interface)以及用于访问新功能的新接口(interface),因此自动设置 JS 接口(interface)并“委托(delegate)”对正确 Silverlight 方法的调用将有助于大大加快工作速度。

我不能在这里发布代码,所以这是摘要。

最佳答案

老实说,如果您在编译时不知道类型,那么创建 Delegate 并没有太多好处。 .你不想使用 DynamicInvoke ;它将与反射一样慢。主要的异常(exception)是当代理类型潜伏在阴影中时,例如订阅事件时 - 在这种情况下 EventInfo使其可用。

有关信息,请在 .NET 3.5 中 Expression , 有:

Expression.GetActionType(params Type[] typeArgs);
Expression.GetFuncType(params Type[] typeArgs)

这可能在一定程度上有所帮助:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
static class Program {
static void Main() {
DoStuff("Test1");
DoStuff("Test2");
}
static void DoStuff(string methodName) {
MethodInfo method = typeof(Program).GetMethod(methodName);
List<Type> args = new List<Type>(
method.GetParameters().Select(p => p.ParameterType));
Type delegateType;
if (method.ReturnType == typeof(void)) {
delegateType = Expression.GetActionType(args.ToArray());
} else {
args.Add(method.ReturnType);
delegateType = Expression.GetFuncType(args.ToArray());
}
Delegate d = Delegate.CreateDelegate(delegateType, null, method);
Console.WriteLine(d);
}
public static void Test1(int i, DateTime when) { }
public static float Test2(string x) { return 0; }
}

关于.net - 从 MethodInfo 构建一个委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1124563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com