2010-10-14 43 views
0

我正在創建一個Func作爲另一個方法的參數輸入,但是如何調用該函數?作爲參數傳入時,在Func中調用方法

下面的代碼描述自己的工作:

我叫富搭配:

Foo(x => x.SlidingExpiration(TimeSpan.FromSeconds(50))); 

我的foo方法:

public void Foo(Func<CacheExpiration, TimeSpan> cacheExpiration) 
{ 
.... 
inside here I want to call RefreshCache, but how?.. cacheExpiration.?? 

} 

的CacheExpiration :)

public class CacheExpiration 
     { 
      TimeSpan timeSpan; 
      bool sliding; 

      public TimeSpan SlidingExpiration(TimeSpan ts) 
      { 
       this.timeSpan = ts; 
       this.sliding = true; 
       return ts; 
      } 
      public TimeSpan AbsoluteExpiration(TimeSpan ts) 
      { 
       this.timeSpan = ts; 
       return ts; 
      } 

      public bool RefreshCache(MetaObject mo) 
      { 
       //some logic.... 
       return true; 
      } 

     } 
+0

這個問題並不完全有意義。函數'Foo'的參數是一個代理,可以根據需要將'CacheExpiration'實例變成'Timespan'。 'Foo'方法沒有引用現有的'CacheExpiration'實例傳遞給委託。你想在什麼'CacheExpiration'對象上調用'RefreshCache'?委託參數如何在這方面提供幫助?它甚至不返回一個'CacheExpiration'對象。 – Ani 2010-10-14 09:12:40

回答

0

如果我正確讀取它,那麼Func cacheExpiration將接收一個CacheExpiration實例並返回一個TimeSpan。所以我可以看到美孚的身體是:

TimeSpan ts = cacheExpiration.SlidingExpiration(TimeSpan.FromSeconds(50)); 
//or 
TimeSpan ts2 = cacheExpiration.AbsoluteExpiration(TimeSpan.FromSeconds(50)); 

這並不在你的榜樣與LAMDA排隊,所以我從猜你真的想cacheExpiration是一個函數功能,需要一個時間跨度和回報TimeSpan。但是這不適用於RefreshCache方法,因爲它需要一個MetaObject並返回一個布爾值。

+0

NServiceBus可以這樣配置: NServiceBus.Configure.With()。Log4Net (a => a.YourProperty =「value」); 爲什麼我不能做類似的事情? Foo(x => x.SlidingExpiration(TimeSpan.FromSeconds(50))); – Janus007 2010-10-19 17:57:28

+0

在visual studio中,您可以通過定義來從NServiceBus獲取.Log4Net 方法的簽名。看起來他們正在傳遞一個函數來配置泛型類型。 – 2010-10-19 20:34:19

1
var ts = cacheExpiration(yourCacheExpiration); 
相關問題