加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 来自Func的身体

发布时间:2020-12-15 04:18:50 所属栏目:百科 来源:网络整理
导读:我如何从功能中获取身体 Funcbool methodCall = () = output.SendToFile(); if (methodCall()) Console.WriteLine("Success!"); 我需要将此“output.SendToFile()”作为字符串 另一个例子 string log = ""; public void FooT(FuncT func) { try { var t = fu
我如何从功能中获取身体
Func<bool> methodCall = () => output.SendToFile(); 
      if (methodCall())
         Console.WriteLine("Success!");

我需要将此“output.SendToFile()”作为字符串

另一个例子

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

解决方法

你不能. A Func< T>没什么可以轻易分析的.如果要分析lambda,则需要创建Expression< Func< bool>>并分析它.

获取表达式的主体很简单:

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

body是一个MethodCallExpression,你可以进一步分析或只是通过ToString输出.使用ToString不会完全符合您的想法,但它也包含该信息.

例如,在LINQPad中对主体执行ToString()会导致如下所示:

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

如您所见,“output.SendToFile()”就在那里.

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

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

可以缩短到这个:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读