2016-10-28 86 views
0

我有一個函數:通功能參數

private static PrivateMessage GetPM() 
{ 
    using (var db = new DBContext()) 
    { 
     var q = CompiledQueries.GetPMByID(db, messageID); 
     if (q == null) return null; 
     return new PrivateMessage(q); 
    } 
} 

我希望通過這個功能作爲一個參數:

var pm = cacheObj.SetIfNotExists(GetPM); 

SetIfNotExists被定義爲:

public T SetIfNotExists<T>(Func<T> getCachableObjectFunction) 

什麼是否需要修改,以便我可以通過messageID作爲參數GetPM()? EG:

private static PrivateMessage GetPM(int messageID) 
+4

變種PM = cacheObj.SetIfNotExists(()=> GetPM(1)); ? – Evk

回答

2

包裝和類型轉換您的輸出是最簡單的方法。

var pm = cacheObj.SetIfNotExists(() => GetPM(1)); 

並改變GetPM頭:

private static PrivateMessage GetPM(int messageID) 
+0

完美謝謝!解決我的下一個問題,即如何爲不同參數輸入的函數做到這一點!只是檢查,以這種方式傳遞它不會援引它嗎? –

+0

你說得對,它不會,但答案可以讓你在'GetPM()'方法中傳遞任意數量的參數。 –

+0

@juharr已更新答案 –