gpt4 book ai didi

c# - 为什么编译器选择使用 IEnumerable 重载而不是 IEnumerable

转载 作者:太空狗 更新时间:2023-10-29 22:06:09 24 4
gpt4 key购买 nike

考虑以下两种扩展方法:

using System;
using System.Collections.Generic;
using System.Linq;

public static class Extensions
{
public static bool Contains(this IEnumerable self, object obj)
{
foreach (object o in self)
{
if (Object.Equals(o, obj))
{
return true;
}
}
return false;
}

public static bool ContainsEither<T>(this IEnumerable<T> self, T arg1, T arg2)
{
return self.Contains(arg1) || self.Contains(arg2);
}
}

当我编写第二个方法时,我打算它调用通用 LINQ Enumerable.Contains<T>方法(从用法推断的类型参数)。但是,我发现它实际上是在调用第一个方法(我的自定义 Contains() 扩展方法。当我注释掉我的 Contains() 方法时,第二个方法编译正常,使用 Enumerable.Contains<T>() 方法。

我的问题是,为什么编译器选择我的 Contains()非泛型方法 IEnumerable争论Enumerable.Contains<T>()IEnumerable<T>争论?我希望它选择 Enumerable.Contains<T>()因为IEnumerable<T>IEnumerable 更派生.

最佳答案

My question is, why does the compiler choose my Contains() method with non-generic IEnumerable argument over Enumerable.Contains<T>() with IEnumerable<T> argument?

因为它位于包含调用它的方法的同一个命名空间中。在该命名空间中声明的类型实际上优先于在导入的命名空间中声明的类型。

来自 C# 5 规范,第 7.6.5.2 节:

The search for C proceeds as follows:

  • Starting with the closest enclosing namespace declaration, continuing with each enclosing namespace declaration, and ending with the containing compilation unit, successive attempts are made to find a candidate set of extension methods:
    • If the given namespace or compilation unit directly contains non-generic type declarations Ci with eligible extension methods Mj, then the set of those extension methods is the candidate set.
    • If namespaces imported by using namespace directives in the given namespace or compilation unit directly contain non-generic type declarations Ci with eligible extension methods Mj, then the set of those extension methods is the candidate set.
  • If no candidate set is found in any enclosing namespace declaration or compilation unit, a compile-time error occurs.

关于c# - 为什么编译器选择使用 IEnumerable 重载而不是 IEnumerable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37889830/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com