【问题标题】:Searching function arguments in lambda在 lambda 中搜索函数参数
【发布时间】:2014-03-28 07:52:22
【问题描述】:

有一个功能:

Func<object, double> calculation = x => Row("1") + Row("2");

其中 Row 是一些提取数据的函数,例如:

 public static double Row(string rowName)
    {
        return 100; // just an example irrelevant in this case
    }

我想提取 Row 函数调用的所有参数。在这种情况下

var parameters = Parse(calculation).ToList();

参数将包含“1”和“2”。我已经开始了:

private IEnumerable<string> Parse(Func<object, double> calculation)
    {

            // and I'm stuck here :) 
    }

我想提取的是值“1”和“2”,目前我被卡住了。任何想法如何解析这样的函数?

【问题讨论】:

  • 请提供更多细节。 Row 的范围到底是什么?你的意思是成为Row 的成员x
  • Row 只是一些函数 public double Row(string rowName){ return 100; } Row 只是一个外部函数,很可能是静态的。如果有帮助,它可能是 x 的成员。现在它只是一个概念:)
  • 理论上可以通过检查 IL,但你最好在这里使用表达式树。
  • 我在考虑表达式树,但我坚持
  • 那么你的代码在语法上似乎是正确的;但我不清楚预期的行为是什么。按照您的示例,calculation 将为每个参数返回 200

标签: c# function lambda


【解决方案1】:

我认为不可能直接使用 .net 将参数传递给委托中的方法。您可以获得的最接近的是反射的GetMethodBody().GetILAsByteArray(),它返回一个字节数组。这本身是没有用的。大意如下。

private IEnumerable<string> Parse(Func<object, double> calculation)
{
    var byteArr = calculation.GetInvocationList().First().Method.GetMethodBody().GetILAsByteArray();

    //returned null so that the method can build
    return null;
}

您可以尝试使用Mono.Cecil 并检查它是否能以任何方式帮助您。我已经尝试过一次,但与您的用户案例不同。以下是一些可能有助于您理解它的帖子。

https://stackoverflow.com/questions/1513319/mono-cecil-documentation-and-tutorials

http://www.bytecodeartist.net/2011/05/introduction-to-il-rewriting-with-cecil.html http://www.codeproject.com/Articles/671259/Reweaving-IL-code-with-Mono-Cecil

一切顺利。

【讨论】:

  • 这并不令人欣慰:/ 我会尝试将它包装在代理函数中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-04
  • 2018-06-27
  • 1970-01-01
  • 2011-12-27
  • 2021-08-30
  • 1970-01-01
相关资源
最近更新 更多