我在重载扩展方法时遇到问题。
我有两个扩展方法:
方法 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/