2012-06-21 84 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) 
相关问题