2010-04-24 30 views
5

我希望能夠寫的東西作爲如何界定謂詞作爲函數參數

void Start(some condition that might evaluate to either true or false) { 
    //function will only really start if the predicate evaluates to true 
} 

我猜它一定是形式的東西:

void Start(Predicate predicate) { 
} 

我怎樣才能檢查裏面我的開始函數,只要謂詞評估爲真或假?我使用的謂詞是否正確?

謝謝

回答

10

下面是一個在函數中使用謂詞的簡單示例。

static void CheckRandomValueAgainstCriteria(Predicate<int> predicate, int maxValue) 
{ 
    Random random = new Random(); 
    int value = random.Next(0, maxValue); 

    Console.WriteLine(value); 

    if (predicate(value)) 
    { 
     Console.WriteLine("The random value met your criteria."); 
    } 
    else 
    { 
     Console.WriteLine("The random value did not meet your criteria."); 
    } 
} 

...

CheckRandomValueAgainstCriteria(i => i < 20, 40); 
2

你可以做這樣的事情:

void Start(Predicate<int> predicate, int value) 
    { 
     if (predicate(value)) 
     { 
      //do Something 
     }   
    } 

在那裏你調用該方法是這樣的:

Start(x => x == 5, 5); 

我不知道這將是多麼有用。 Predicates是東西非常方便的像過濾列表:

List<int> l = new List<int>() { 1, 5, 10, 20 }; 
var l2 = l.FindAll(x => x > 5); 
1

從設計的角度來看,謂詞的目的被傳遞給函數通常是過濾掉一些IEnumerable的,正在對每個元素進行測試謂詞,以確定是否item是過濾後的集合的成員。

你最好在你的例子中簡單地用一個布爾返回類型的函數。

相關問題