扩展方法。类型或命名空间'T'未找到。

9
我有以下代码,我正在.NET 4.0项目中编译。
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?) 
2个回答

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声明(所有其他T都是从中推断出来的)。

谢谢,现在我也学到了一些新东西。我也在尝试弄清楚这个问题。 - Shane van Wyk

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接