Logarithmic lambda expressions

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

In the When method, I would like to register when a predicate or Func<bool> returns false. However, just writing β€œcondition not fulfilled” does not give me much information. If I call the method as follows:

 demo.When(x => x.Name == "John"); 

Is there a way to convert this expression to a human-readable / meaningful string for logging?

+6
source share
1 answer

There is not a lot of useful metadata in regular lambda. Instead, you can use expression trees:

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

Then on the call site:

  When(x => false); 

And the output will be:

Condition not met: x => False

However, expression trees introduce a lot more overhead, and condition.Compile also not cheap. Therefore, I do not recommend this approach at all, but it will display useful information as you want.

+10
source

Source: https://habr.com/ru/post/911966/


All Articles