如果我有一个实现多个接口的类型,并且我的类型实现的接口类型有多个同名的扩展方法,那么什么决定了使用哪个扩展方法?
对于
List<T>
,如果我有ICollection<T>
和IEnumerable<T>
的扩展方法,那么ICollection<T>
优先。如果我添加另一个需要 IList<T>
的扩展,那么 IList<T>
优先于其他两种方法。我想也许它们在类中声明的顺序就是原因,但事实并非如此,因为 IList<T>
出现在类定义中的其他两个之后。
这是我用来测试的代码:
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var myList = new List<int>();
myList.IsNullOrEmpty(); // IList is used
// Layout for List<T> in constructor
//
// public class List<T> :
// ICollection<T>,
// IEnumerable<T>,
// ...,
// IList<T>,
// ...
}
}
public static class Extensions
{
public static bool IsNullOrEmpty<T>(this ICollection<T> collection)
{
Console.WriteLine("ICollection used.");
return collection?.Count == 0;
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable)
{
Console.WriteLine("IEnumerable used.");
return enumerable == null || !enumerable.Any();
}
public static bool IsNullOrEmpty<T>(this IList<T> list)
{
Console.WriteLine("IList used.");
return list?.Count == 0;
}
}
我找到了答案。
IList<T>
实现了 ICollection<T>
和 IEnumerable<T>
,因此它优先于那些。并且,ICollection<T>
实现了IEnumerable<T>
,所以它优先于它。
IList<T>
文档
ICollection<T>
文档