C#将Lambda表达式函数转换为描述性字符串

Kyl*_*yle 4 c# lambda

我有一个非常不必要的困境.我懒洋洋地寻找一个将lamda表达式转换为字符串的函数.我每次都在输入这个缓存密钥让我感到困扰,但我真的不想花时间去创建它.

我想用它来创建我创建的缓存函数:

如果我想在没有每次调用函数的情况下为某个人获取名称的话.

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

GetExpressionDescription将返回"PersonProvider.GetById(int 10)"

我认为这是可能的,但我想知道是否有人已经建立了这个或已经在某处看到它.

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;
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*bes 5

你可以简单地得到一个的字符串表示Expression<>.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();
    }
}
Run Code Online (Sandbox Code Playgroud)

打印:

s => s.StartsWith("A")

请参阅:https://dotnetfiddle.net/CJwAE5

但是当然它不会让你调用者和变量的值,只是表达式本身.