2015-10-16 50 views
3

我傾向於delagate和lambda表達式。我寫了一些測試代碼,使用Count(),一些調用工作,但最後不工作,我不知道爲什麼。請幫我解釋一下。謝謝。謂詞不起作用的代表

public static int Count<T>(T[] arr, Predicate<T> condition) 
{ 
    int counter = 0; 
    for (int i = 0; i < arr.Length; i++) 
     if (condition(arr[i])) 
      counter++; 
    return counter; 
} 

delegate Boolean IsOdds<T>(T x); 
delegate bool IsEven(int x); 

private void button1_Click(object sender, EventArgs e) 
{ 
    IsOdds<int> isOdds = i => i % 2 == 1;//must be <int>, not <T> 
    IsEven isEven = i => i % 2 == 0;    

    Action<int> a = x => this.Text = (x*3).ToString(); 
    a(3); 

    Predicate<int> f = delegate(int x) { return x % 2 == 1; }; 
    Predicate<int> ff = x => x % 2 == 1; 

    MessageBox.Show("lambada " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, x => x % 2 == 1).ToString()); 
    MessageBox.Show("f " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, f).ToString()); 
    MessageBox.Show("ff " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, ff).ToString()); 
    MessageBox.Show("delegate " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, delegate(int x) { return x % 2 == 1; }).ToString()); 
    MessageBox.Show(Count<int>(new int[] { 1, 2, 3, 4, 5 }, isOdds(int x)).ToString()); //this is wrong 
    MessageBox.Show(Count<int>(new int[] { 1, 2, 3, 4, 5 }, isEven(int x)).ToString()); //this is wrong 
    return; 
} 
+0

非常感謝你。 – peter

回答

3
Count<int>(new int[] { 1, 2, 3, 4, 5 }, isOdds(int x)); 

這是無效的。 isOdds返回bool並且取整數並且其必須像Predicate<int>。但你不能直接發送它,因爲它們不是同一類型。你必須使用另一個lambda。

Count<int>(new int[] { 1, 2, 3, 4, 5 }, x => isOdds(x)); // x => isOdds(x) is now type of Predicate<int> 

同樣的事情ISEVEN

也有另一種方式。你可以創建新的謂詞。

Count<int>(new int[] { 1, 2, 3, 4, 5 }, new Predicate<int>(isOdds)); 
+0

非常感謝 – peter

0

基本上delegate Boolean IsOdds<T>(T x)相當於Predicate<T>delegate bool IsEven(int x)相當於Predicate<int> 所以,你可以忽略自己的代表聲明,寫這樣的事:

private void button1_Click(object sender, EventArgs e) 
    { 
     Predicate<int> isOdds = i => i % 2 == 1; 
     Predicate<int> isEven = i => i % 2 == 0; 

     Action<int> a = x => this.Text = (x * 3).ToString(); 
     a(3); 

     Predicate<int> f = delegate (int x) { return x % 2 == 1; }; 
     Predicate<int> ff = x => x % 2 == 1; 

     MessageBox.Show("lambada " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, x => x % 2 == 1).ToString()); 
     MessageBox.Show("f " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, f).ToString()); 
     MessageBox.Show("ff " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, ff).ToString()); 
     MessageBox.Show("delegate " + Count<int>(new int[] { 1, 2, 3, 4, 5 }, delegate (int x) { return x % 2 == 1; }).ToString()); 
     MessageBox.Show(Count<int>(new int[] { 1, 2, 3, 4, 5 }, isOdds).ToString()); 
     MessageBox.Show(Count<int>(new int[] { 1, 2, 3, 4, 5 }, isEven).ToString()); 
    }