重载泛型扩展方法

本文关键字:方法 扩展 泛型 重载 | 更新日期: 2023-09-27 18:35:36

我在重载扩展方法时遇到问题。

我有两种扩展方法:

方法 A - 对于标准对象:

public static bool HasChanged<T>(this T obj1, T obj2, Func<T, T, bool> equalityExpression)

方法 B - 对于 IEnumerables:

public static bool HasChangedList<T>(this IEnumerable<T> obj1, IEnumerable<T> obj2, Func<T, T, bool> isEqualExpression)

但是我想给它们两个相同的名称,目前不起作用,因为 IEnumerables 也是对象,因此编译器无法决定是在 IEnumerable 上使用第一个还是第二个。

我敢肯定,不可能让第一个方法接受除 IEnumerable 之外的所有对象,那么还有另一种方法吗?

重载泛型扩展方法

(不是真正的解决方案,但太长了,无法发表评论。希望 C# 规范大师之一会出现并告诉我们为什么重载解决方案在这种特殊情况下是这样工作的。

如果

  • 您限定了相等表达式的参数,或者如果
  • IEnumerable 的内部类型可以从 lambda 表达式中推断出来,

它应该可以正常工作:

class Program
{
    static void Main(string[] args)
    {
        var array = new[] { 1, 2, 3 };
        // uses the IEnumerable overload -- prints false
        Console.WriteLine(array.HasChanged(array, (int x, int y) => x == y));
        // uses the IEnumerable overload -- prints false
        Console.WriteLine(array.HasChanged(array, (x, y) => x >= y));
        // uses the generic overload -- prints true
        Console.WriteLine(array.HasChanged(array, (x, y) => x == y));
        Console.ReadLine();
    }
}
static class Extensions
{
    public static bool HasChanged<T>(this IEnumerable<T> obj1, IEnumerable<T> obj2, Func<T, T, bool> isEqualExpression)
    { 
        return false; 
    }
    public static bool HasChanged<T>(this T obj1, T obj2, Func<T, T, bool> equalityExpression)
    { 
        return true; 
    }
}