Func< T>的身体 [英] Body from Func<T>

查看:98
本文介绍了Func< T>的身体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从功能中获取身体

Func<bool> methodCall = () => output.SendToFile(); 

if (methodCall())
    Console.WriteLine("Success!");

我需要将此output.SendToFile()作为字符串获取

I need to get this output.SendToFile() as a string

另一个例子:

string log = "";

public void Foo<T>(Func<T> func)
{
    try
    {
        var t = func();
    }
    catch (Exception)
    {
        //here I need to add the body of the lambda
        // log += func.body;
    }
}

public void Test()
{
    var a = 5;
    var b = 6;
    Foo(() => a > b);
}

有关此主题的更多信息,请参见:表达式树

For more information on this topic see: Expression Trees

推荐答案

您不能. Func<T>是您可以轻松分析的任何内容.如果要分析lambda,则需要创建一个Expression<Func<bool>>并对其进行分析.

You can't. A Func<T> is nothing you can easily analyze. If you want to analyze a lambda, you need to create a Expression<Func<bool>> and analyze it.

获取表达式主体很简单:

Getting the body of an expression is simple:

Expression<Func<bool>> methodCall = () => output.SendToFile(); 
var body = methodCall.Body;

body将是MethodCallExpression,您可以进一步分析或仅通过ToString输出.使用ToString不会完全得到您想要的东西,但是它也包含该信息.

body would be a MethodCallExpression you could further analyze or just output via ToString. Using ToString won't result exactly in what you would like to have, but it contains that information, too.

例如,在LINQPad中在body上执行ToString()会导致如下结果:

For example, executing ToString() on body in LINQPad results in something like this:

value(UserQuery+<>c__DisplayClass0).output.SendToFile()

如您所见,"output.SendToFile()"就在其中.

要实际执行表达式定义的代码,您首先需要对其进行编译:

To actually execute the code defined by an expression, you first need to compile it:

var func = methodCall.Compile();
func();

可以缩短为:

methodCall.Compile()(); // looks strange but is valid.

这篇关于Func&lt; T&gt;的身体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆