我有一个完全不必要的困境。我正在懒洋洋地寻找一个可以将 lamda 表达式转换为字符串的函数。我每次都在输入这个缓存键,但我真的不想花时间创建它,这让我很困扰。
我想将它用于我创建的缓存函数:
如果我想在不每次都调用该函数的情况下获取一个人的名字。
public static string GetPersonName(int id)
{
return Repository.PersonProvider.Cached(x => x.GetById(id)).Name;
}
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;
}
最佳答案
您可以简单地获取 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();
}
}
打印:
s => s.StartsWith("A")
参见:https://dotnetfiddle.net/CJwAE5
当然,它不会为您提供调用者和变量的值,只会为您提供表达式本身。
关于C# 将 Lambda 表达式函数转换为描述性字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8215449/