相关疑难解决方法(0)

通用扩展方法解析失败

以下程序无法编译,因为在出​​错的行中,编译器选择使用单个T参数作为分辨率的方法,该方法失败,因为List<T>它不符合单个的通用约束T.编译器无法识别可以使用的其他方法.如果我删除单一T方法,编译器将正确地找到许多对象的方法.

我读过有关泛型方法的高分辨率双向博客文章,一个来自JonSkeet 这里和另一名来自埃里克利珀这里,但我无法找到一个解释或解决我的问题的一种方式.

显然,使用两个具有不同名称的方法会起作用,但我喜欢这样一个事实:对于这些情况,您只有一种方法.

namespace Test
{
  using System.Collections.Generic;

  public interface SomeInterface { }

  public class SomeImplementation : SomeInterface { }

  public static class ExtensionMethods
  {
    // comment out this line, to make the compiler chose the right method on the line that throws an error below
    public static void Method<T>(this T parameter) where T : SomeInterface { }

    public static void Method<T>(this IEnumerable<T> parameter) where T : SomeInterface …
Run Code Online (Sandbox Code Playgroud)

c# generics extension-methods overload-resolution

5
推荐指数
1
解决办法
586
查看次数