如何检查C#lambda表达式是否为“空”?

时间:2017-03-05 16:32:26

标签: c# function lambda

大家好日子!比方说,我有一个函数,包含2个变体的lambda表达式:

DoSomething('a', x => { });
DoSomething('b', x => { Console.WriteLine(x); })

在程序中,我需要根据表达式中的方法是否包含某些代码来执行某些操作。在我看来,它必须看起来像这样:

 public void DoSomething (char symbol, Action<string> execute)
    {
        if (execute.Method.IsEmpty)
            DoThis(...)
        else 
            DoThat(...)
    }

但是,当然,我无法写出这一点。那么,我该如何检查函数中是否有命令?

2 个答案:

答案 0 :(得分:0)

似乎有两种不同的方法:

public void DoSomething (char symbol)
{
    DoThis()
}

public void DoSomething (char symbol, Action<string> execute)
{
    if (execute == null) /* handle null case */ 
        DoThis()
    else 
        DoThat()
}

另一个选项可能是可选参数(你应该检查任何一种方法):

public void DoSomething (char symbol, Action<string> execute = null)
{
    if (execute == null)
        DoThis()
    else 
        DoThat()
}

答案 1 :(得分:-1)

您可以尝试查看相应的IL操作:

public void DoSomething(char symbol, Action<string> execute)
{
    byte[] body = execute.Method.GetMethodBody().GetILAsByteArray();
    if ((body.Length == 1 && body[0] == 42) || (body.Length == 2 && body[0] == 0 && body[1] == 42))
    {
        // 0 - no op
        // 42 - return
        DoThis(...)
    }
    else
    {
        DoThat(...)
    }
}
相关问题