C # Convert Lambda expression function to descriptive string

I have a pretty unnecessary dilemma. I am lazily looking for a function that converts a lamda expression to a string. It bothers me that every time I type this cache key, but I do not want to waste time creating it.

I want to use it for the caching function I created:

Where would I like to get a name for a person without calling a function every time.

public static string GetPersonName(int id) { return Repository.PersonProvider.Cached(x => x.GetById(id)).Name; } 

GetExpressionDescription will return "PersonProvider.GetById (int 10)"

I believe this is possible, but I wonder if anyone has already built it or seen it somewhere.

 public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, double hours = 24) { var expressionDescription = GetExpressionDescription(function); return Cached(function, expressionDescription, hours); } public static R Cached<T, R>(this T obj, Expression<Func<T, R>> function, string cacheName, double hours = 24) { var context = HttpContext.Current; if (context == null) return function.Compile().Invoke(obj); R results = default(R); try { results = (R)context.Cache[cacheName]; } catch { } if (results == null) { results = function.Compile().Invoke(obj); if (results != null) { context.Cache.Add(cacheName, results, null, DateTime.Now.AddHours(hours), Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } } return results; } 
+4
source share
2 answers

You can simply get the string representation of Expression<> with .ToString() :

 using System; using System.Linq.Expressions; public class Program { public static void Main() { Test(s => s.StartsWith("A")); } static void Test(Expression<Func<string,bool>> expr) { Console.WriteLine(expr.ToString()); Console.ReadKey(); } } 

Print

s => s.StartsWith ("A")

See: https://dotnetfiddle.net/CJwAE5

But of course, this will not give you the caller and the values ​​of the variables, just the expression itself.

+5
source

Maybe you should try DynamicExpresso. I used this library to develop a lightweight business rule engine.

https://github.com/davideicardi/DynamicExpresso

+1
source

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


All Articles