4

编辑:我在原来的问题中犯了一个错误。它应该是关于方法LastLastOrDefault(或SingleSingleOrDefault,或FirstFirstOrDefault - 很多!)。

这个问题的启发,我打开了 Reflector 并查看了代码

Enumerable.Last<T>(this collection)

然后我跳到代码

Enumerable.LastOrDefault<T>(this collection)

我看到完全相同的一段代码(大约 20 行),只有最后一行不同(第一个方法返回默认值(T),第二个方法抛出异常)。

我的问题是为什么会这样?为什么微软的人允许在 .Net 框架内复制重要的代码片段?他们没有代码审查吗?

4

1 回答 1

4

事实上,它们并不完全相同。第一个是这样的:

public static TSource Last<TSource>(this IEnumerable<TSource> source)
{
    if (source == null) throw Error.ArgumentNull("source");

    IList<TSource> list = source as IList<TSource>;
    if (list != null) {
        int count = list.Count;
        if (count > 0) return list[count - 1];
    } else {
        using (IEnumerator<TSource> enumerator = source.GetEnumerator()) {
            if (enumerator.MoveNext()) {
                TSource current;
                do { current = enumerator.Current;}
                while (enumerator.MoveNext());

                return current;
            }
        }
    }
    throw Error.NoElements();
}

另一个是这样的:

public static TSource Last<TSource>(this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");

    TSource last = default(TSource);
    bool foundOne = false;
    foreach (TSource value in source) {
        if (predicate(value)) {
            last = value;
            foundOne = true;
        }
    }
    if (!foundOne) throw Error.NoMatch();
    return last;
}

PS:我希望我现在没有侵犯任何版权。:S

于 2009-09-05T04:27:56.200 回答