2010-03-15 44 views
6

我需要傳入一個謂詞,我可以隨時調用它(就像委託人一樣)。我試圖做這樣的事(我想謂詞代表會滿足我的需求):將bool條件傳遞給我可以在需要時調用的方法

MyMethod(Predicate,string> pred); 

調用,如:MyMethod(s => s.Length > 5);

我想寫的條件直列但調用它時,我想,就像代表。我怎麼能這樣做?

感謝

+0

你只是這樣做! – Grzenio 2010-03-15 16:00:57

回答

2

像下面

bool MyMethod(Predicate<string> pred) { 
    ... 
    if (pred("foo")) { ... 
    } 
} 

然後

MyMethod(s => s.Length > 5); 
3

你會做它就像你寫道:

void MyMethod(Func<string, bool> method) // Could be Predicate<string> instead 
{ 
    // Do something 
    // ... 
    // Later, if you choose to invoke your method: 

    if(method(theString)) 
    { 
     //... 
    } 
} 
相關問題