2011-11-21 160 views
4

我有一個非常不必要的困境。我懶洋洋地尋找一個將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; 
} 
+2

可能重複(http://stackoverflow.com/questions/4793981/converting-expressiont-bool-to-string) –

+1

不能你只需要調用的ToString( )? –

回答

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(); 
    } 
} 

打印:

S => s.StartsWith( 「A」)

參見:https://dotnetfiddle.net/CJwAE5

但它當然不會讓你的調用者和變量的值,只是表達式本身。

+0

同意 - 對我來說,我發現如果.ToString()不足以滿足我需要,我可能會做錯了。 – moarboilerplate

1

也許你應該試試DynamicExpresso。我使用該庫來開發輕量級業務規則引擎。 [轉換表達 爲String]的

https://github.com/davideicardi/DynamicExpresso

+0

我們爲什麼不試試「DynamicExpresso」?減號是否來自專家,他有很多事情要教給別人?任何貢獻都應該受到歡迎。 –

相關問題