2013-07-25 79 views
9

我有以下的代碼,我在.NET 4.0項目擴展方法。類型或命名空間名稱「T」找不到

public static class Ext 
{ 
    public static IEnumerable<T> Where(this IEnumerable<T> source, Func<T, bool> predicate) 
    { 
     if (source == null) 
     { 
      throw new ArgumentNullException("source"); 
     } 
     if (predicate == null) 
     { 
      throw new ArgumentNullException("predicate"); 
     } 
     return WhereIterator(source, predicate); 
    } 

    private static IEnumerable<T> WhereIterator(IEnumerable<T> source, Func<T, bool> predicate) 
    { 
     foreach (T current in source) 
     { 
      if (predicate(current)) 
      { 
       yield return current; 
      } 
     } 
    } 
} 

正在編制,但得到以下錯誤。 System.dll已經包含在引用中作爲默認值。我可能做錯了什麼?

Error 1 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) 

Error 2 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) 

Error 3 The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) 

回答

23

嘗試:

public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) 

而且

private static IEnumerable<T> WhereIterator<T>(IEnumerable<T> source, Func<T, bool> predicate) 

總之,你錯過了通用牛逼聲明方法簽名(其它所有T的是從推斷)。

+0

Thanx現在我學到了新的東西。正在嘗試弄清楚這一點 –

5

你錯過了泛型方法定義:

public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate) 
{ 
    if (source == null) 
    { 
     throw new ArgumentNullException("source"); 
    } 
    if (predicate == null) 
    { 
     throw new ArgumentNullException("predicate"); 
    } 
    return WhereIterator(source, predicate); 
} 

private static IEnumerable<T> WhereIterator<T>(IEnumerable<T> source, Func<T, bool> predicate) 
{ 
    foreach (T current in source) 
    { 
     if (predicate(current)) 
     { 
      yield return current; 
     } 
    } 
} 

注意方法名稱後的<T>

相關問題