c# - 重载通用扩展方法

标签 c# extension-methods

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

我有两个扩展方法:

方法 A - 对于标准对象:

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

方法 B - 对于 IEnumerable:

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

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

我确信,不可能让第一个方法接受除 IEnumerable 之外的所有对象,那么还有其他方法吗?

最佳答案

(这并不是一个真正的解决方案,但评论太长了。希望 C# 规范专家之一能够出现并告诉我们为什么重载解析在这种特殊情况下会这样工作。)

如果

  • 您限定 equalExpression 的参数如果
  • 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; 
    }
}

关于c# - 重载通用扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27704943/

相关文章:

c# DateTime 添加不带扩展方法的属性

c# - 现有的类似于Parallel.For的LINQ扩展方法?

c# - 数组内存分配说明

c# - Monotouch.Dialog:如何从 RadioGroup 中预选一个元素?

java - 如何正确编写 C# 帮助程序类以从单行读取多个整数?

c# - 如何使接口(interface)上的扩展方法在所有实现类上可用?

C# - 对 IEnumerable<T> 的操作

extension-methods - 来自外部库的实用程序类的扩展方法

c# - 为什么我在 SignalR 上收不到以复杂对象作为参数的事件?

javascript - 使用 jquery 将数据发送到 MVC Controller