有什么办法可以使扩展方法优先于泛型方法吗?

Is there any way I can make an extension method take priority over a generic method?

在 .NET 中,如果有 class 方法 Foo<T>(T t)(无约束)和方法 Foo(string s),调用 Foo("test") 调用 Foo 接受 string。这一切都很好,除非 string 重载是一个扩展方法,在这种情况下总是调用通用版本。是否有解决此问题的方法,还是我运气不好?

简答:

C# 5.0 Language Specification的第163页,我们可以看到,在Method Group(一组重载方法)上尝试了所有重载决议后,没有找到合适的候选者,编译器将尝试搜索适用的扩展方法。这意味着所有时髦的东西,如泛型类型推断,都将优先于扩展方法。引用:

If the resulting set of candidate methods is empty, then further processing along the following steps are abandoned, and instead an attempt is made to process the invocation as an extension method invocation (§7.6.5.2). If this fails, then no applicable methods exist, and a binding-time error occurs.