【问题标题】:Convert B(C(),D()) to (c,d)=>B(()=>c(),()=>d()) - Generating delegate wrappers from MethodInfos?将 B(C(),D()) 转换为 (c,d)=>B(()=>c(),()=>d()) - 从 MethodInfos 生成委托包装?
【发布时间】:2011-05-01 03:42:00
【问题描述】:

最终,我期待一种基于反射的方法来为方法 B(C(),D()) 创建委托包装器 - 类似于 (c,d)=>B(()= >c(),()=>d())

第一个问题 - 鉴于您有 Methodinfo,创建与该方法签名相对应的委托类型(通过反射)有哪些注意事项?

您是否参考了任何这样做的开源项目的代码块? :P

更新:这是为 methodinfo Builds a Delegate from MethodInfo? 创建委托的通用方法 - 我认为递归包装参数部分是我周末必须解决的问题。

【问题讨论】:

  • 很高兴您期待它。玩得开心。 ;)
  • 只是闲逛并寻找 joskeet :P
  • 为什么要提供另一层不必要的间接?
  • 听起来你正在尝试 Eric 目前正在解释的东西 in his blog
  • @leppie 无聊的聪明人是危险的

标签: c# .net reflection methods delegates


【解决方案1】:

使用Expression 构建动态方法。这是根据您的问题的示例。我以Console.Write(string s) 为例。

    MethodInfo method = typeof(Console).GetMethod("Write", new Type[] { typeof(string) });
    ParameterExpression parameter = Expression.Parameter(typeof(string),"str");
    MethodCallExpression methodExp = Expression.Call(method,parameter);
    LambdaExpression callExp = Expression.Lambda(methodExp, parameter);
    callExp.Compile().DynamicInvoke("hello world");

【讨论】:

【解决方案2】:

我设法从这样的方法的 MethodInfo 创建了一个工作委托:

方法和委托:

public static int B(Func<int> c, Func<int> d) {
  return c() + d();
}

public delegate int TwoFunc(Func<int> c, Func<int> d);

代码:

MethodInfo m = typeof(Program).GetMethod("B");
TwoFunc d = Delegate.CreateDelegate(typeof(TwoFunc), m) as TwoFunc;
int x = d(() => 1, () => 2);
Console.WriteLine(x);

输出:

3

虽然不确定它有多大用处......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多