private static void TestAmbiguousGenerics()
{
var string1 = "Hello".Foo(s => s + " world"); // works
int? n = 123;
var string2 = n.Foo(x => (x + 1).ToString()); // compiler error
Console.WriteLine("{0} {1}".Fmt(string1, string2));
}
public static string Foo<T>(this T obj, Func<T, string> func) where T : class
{
return obj == null ? "" : func(obj);
}
public static string Foo<T>(this T? str, Func<T, string> func) where T : struct
{
return str == null ? "" : func(str.Value);
}
编译器无法判断我是否在调用 Foo<T>
的第一个重载其中 T
是Nullable<int>
,或第二个重载,其中 T
是int
.显然我可以通过显式调用 n.Foo<int>()
来完成这项工作, 但有没有办法让第一个重载排除 Nullable<>
从什么限制T
可以吗?
最佳答案
否——两种方法都适用于重载决议;仅在选择最佳重载之后检查类型参数约束。
有一个 really evil way of working round this但就我个人而言,我或者给这两个方法不同的名称或者明确提供类型参数。
关于c# - 如何解决通用扩展方法中的这种歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21157391/