我有一个非常不必要的困境。我懒洋洋地寻找一个将lamda表达式转换为字符串的函数。它困扰我,我每次都在输入这个缓存键,但我并不想花时间来创建它。C#将Lambda表达式函数转换为描述性字符串
我想使用它的缓存功能,我创建:
在哪里,如果我想获得一个人的名称,而不每次调用该函数。
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;
}
可能重复(http://stackoverflow.com/questions/4793981/converting-expressiont-bool-to-string) –
不能你只需要调用的ToString( )? –