编译器无法在具有不同where条件的通用扩展方法之间进行选择

时间:2014-07-17 12:29:59

标签: c# linq generics

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication8
{
  public interface MyBaseClass { }

  public interface MyClass1 : MyBaseClass { }

  public interface MyClass2 : MyBaseClass { }

  public interface Filter { int Id { get; set; } }

  public interface Filter1 : Filter { }

  public interface Filter2 : Filter { }

  public static class DbExt
  {
    public static IQueryable<T> WhereHistory<T>(this IQueryable<T> source, Func<Filter1, bool> expr) where T : MyClass1
    {
      Console.WriteLine("WhereEntityHistory");
      return source;
    }
  }

  public static class DocExt
  {
    public static IQueryable<T> WhereHistory<T>(this IQueryable<T> source, Func<Filter2, bool> expr) where T : MyClass2
    {
      Console.WriteLine("WhereEntityHistory");
      return source;
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      IQueryable<MyClass1> query1 = (new List<MyClass1>()).AsQueryable();
      query1 = query1.WhereHistory(h => h.Id == 0);

      IQueryable<MyClass2> query2 = (new List<MyClass2>()).AsQueryable();
      query2 = query2.WhereHistory(h => h.Id == 7);
    }
  }
}

此代码编译时出错:

  

以下方法或属性之间的调用不明确:   &#39; ConsoleApplication8.DbExt.WhereHistory(System.Linq.IQueryable,   System.Func)&#39;和   &#39; ConsoleApplication8.DocExt.WhereHistory(System.Linq.IQueryable,   System.Func)&#39;

由于条件的原因,呼叫并不含糊。我该如何解决?

3 个答案:

答案 0 :(得分:5)

通用约束不是函数签名的一部分,因此为了区分它们,您需要将它们称为静态方法(或者给它们指定不同的名称)。

  

方法类型推断算法仅考虑是否可以从参数类型一致推断方法类型参数。

来源:Eric Lippert

答案 1 :(得分:1)

对泛型的限制是not part of the signature

答案 2 :(得分:-1)

如果您想按where T : MyClass1进行过滤,为什么不删除泛型并使用

   public static IQueryable<MyClass1> WhereHistory(this IQueryable<MyClass1> source, Func<Filter1, bool> expr)
相关问题