2012-06-21 163 views
29

我有以下我在.NET 4.0項目類型或命名空間名稱「T」找不到

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

     } 
    } 

    public static class Utility 
    { 
     public static IEnumerable<T> Filter1(this IEnumerable<T> input, Func<T, bool> predicate) 
     { 
      foreach (var item in input) 
      { 
       if (predicate(item)) 
       { 
        yield return item; 
       } 
      } 
     } 
    } 
} 

正在編譯代碼,但得到以下錯誤。 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?) 

回答

28
public static class Utility 
{ 
    public static IEnumerable<T> Filter1<T>(// Type argument on the function 
     this IEnumerable<T> input, Func<T, bool> predicate) 
    { 

如果您如果一個不小心擴展方法與否,你可以添加一個通用的約束類。我的猜測是你想要的擴展方法。

public static class Utility<T> // Type argument on class 
{ 
    public static IEnumerable<T> Filter1(// No longer an extension method 
     IEnumerable<T> input, Func<T, bool> predicate) 
    { 
+0

+1,我假定你不能做一個靜態類通用。 –

+0

@PaulPhillips - 我其實只是試過了,我不認爲你可以。我刪除了這部分答案。 – SwDevMan81

+0

我在linqpad上工作,雖然調用很笨拙。你必須做'Utility .Filter()' –

41

你必須把類型參數放在函數本身。

public static IEnumerable<T> Filter1<T>(...) 
+0

一個天真的問題,爲什麼不是類型推斷足夠聰明,弄清楚它? 'IEnumerable input'作爲參數傳入,所以'T'在執行時已知。 – foresightyj

14

您需要聲明T,它發生在方法名稱或類名稱後面。你的方法聲明更改爲:

public static IEnumerable<T> 
    Filter1<T>(this IEnumerable<T> input, Func<T, bool> predicate) 
相關問題