c# - 如何解决通用扩展方法中的这种歧义?

标签 c# generics extension-methods

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> 的第一个重载其中 TNullable<int> ,或第二个重载,其中 Tint .显然我可以通过显式调用 n.Foo<int>() 来完成这项工作, 但有没有办法让第一个重载排除 Nullable<>从什么限制T可以吗?

最佳答案

否——两种方法都适用于重载决议;仅在选择最佳重载之后检查类型参数约束。

有一个 really evil way of working round this但就我个人而言,我或者给这两个方法不同的名称​​或者明确提供类型参数。

关于c# - 如何解决通用扩展方法中的这种歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21157391/

相关文章:

swift - 为所有 rest api 服务声明一个通用函数

generics - F# 通用记录

c# - 我们如何扩展所有枚举类型?

c# - 如何获取 LightSwitch 中 IContentItemProxy 上的 SetBinding 方法的路径?

c# - POST 提交的表单显示 URL 中的值。难道不应该把他们藏起来吗?

c# - 使用 Parallel 创建绑定(bind)项时 CollectionViewSource.SortDescriptions 不起作用

Java:泛型继承

c# - 将简单绑定(bind)到“文本属性”的解决方案扩展到多个控件以处理与任何类型的绑定(bind)?

c# - List<T> 上的通用排序

c# - Xamarin Forms Maps - 在 iOS 上显示当前位置