Body from Func<T>

懵懂的女人 提交于 2019-12-23 09:34:51

问题


how can I get a body from function

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

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

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

Another example:

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);
}

Edit: For more information on this topic see: Expression Trees


回答1:


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 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.

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

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

As you can see, "output.SendToFile()" is there.

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

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

Which can be shortened to this:

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


来源:https://stackoverflow.com/questions/17673849/body-from-funct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!