记录lambda表达式

niv*_*lam 8 c# lambda

public class Demo
{       
    public void When(Func<Person, bool> condition)
    {
        if (!condition)
        {
            Log.Info("Condition not met.");
            return;
        }

        // Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

When方法中,我想记录谓词或Func<bool>返回false.但是,只记录"未满足的条件"并没有给我太多信息.如果我这样调用方法:

demo.When(x => x.Name == "John");
Run Code Online (Sandbox Code Playgroud)

有没有办法将该表达式转换为可读/有意义的字符串以进行日志记录?

Kir*_*oll 12

在普通的lambda中没有太多有用的元数据.您可以使用表达式树:

void When(Expression<Func<Person, bool>> condition)
{
    var person = new Person();
    if (!condition.Compile()(person))
    {
        Console.WriteLine("Condition not met: " + condition);
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在呼叫站点:

 When(x => false);
Run Code Online (Sandbox Code Playgroud)

输出将是:

条件未达到:x => False

然而,表达式树引入了更多的开销,并且condition.Compile也不便宜.所以我一般不推荐这种方法,但它会输出你想要的有用信息.