【问题标题】:Extension Methods not working for an interface扩展方法不适用于接口
【发布时间】:2008-09-17 12:14:31
【问题描述】:

受 MVC 店面的启发,我正在进行的最新项目是使用 IQueryable 上的扩展方法来过滤结果。

我有这个界面;

IPrimaryKey
{
  int ID { get; }
}

我有这个扩展方法

public static IPrimaryKey GetByID(this IQueryable<IPrimaryKey> source, int id)
{
    return source(obj => obj.ID == id);
}

假设我有一个类 SimpleObj,它实现了 IPrimaryKey。当我有一个 SimpleObj 的 IQueryable 时,GetByID 方法不存在,除非我明确地将其转换为 IPrimaryKey 的 IQueryable,这不太理想。

我错过了什么吗?

【问题讨论】:

    标签: c# .net extension-methods


    【解决方案1】:

    如果操作正确,它会起作用。 cfeduke 的解决方案有效。但是,您不必将IPrimaryKey 接口设为通用,实际上,您根本不必更改原始定义:

    public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey
    {
        return source(obj => obj.ID == id);
    }
    

    【讨论】:

    • 非常好 - 我不接受原始答案。我明天试试这个。谢谢你们。
    • 我只想说我的答案没有错,这是他的代码不起作用的原因,我只是没有花时间制定解决方案。对你更好的答案投了赞成票。
    • public static T GetByID(this IQueryable source, int id) where T : IPrimaryKey // 更好的集成
    【解决方案2】:

    编辑:Konrad 的解决方案更好,因为它更简单。下面的解决方案有效,但仅在类似于 ObjectDataSource 的情况下才需要,在这种情况下,通过反射检索类的方法,而无需遍历继承层次结构。显然这不会发生在这里。

    这是可能的,当我设计用于使用 ObjectDataSource 的自定义实体框架解决方案时,我不得不实现类似的模式:

    public interface IPrimaryKey<T> where T : IPrimaryKey<T>
    {
        int Id { get; }
    }
    
    public static class IPrimaryKeyTExtension
    {
         public static IPrimaryKey<T> GetById<T>(this IQueryable<T> source, int id) where T : IPrimaryKey<T>
         {
             return source.Where(pk => pk.Id == id).SingleOrDefault();
         }
    }
    
    public class Person : IPrimaryKey<Person>
    {
        public int Id { get; set; }
    }
    

    使用片段:

    var people = new List<Person>
    {
        new Person { Id = 1 },
        new Person { Id = 2 },
        new Person { Id = 3 }
    };
    
    var personOne = people.AsQueryable().GetById(1);
    

    【讨论】:

      【解决方案3】:

      由于泛型不具备遵循继承模式的能力,这无法正常工作。 IE。 IQueryable 不在 IQueryable

      的继承树中

      【讨论】:

        猜你喜欢
        • 2019-04-23
        • 2015-12-17
        • 2019-09-23
        • 1970-01-01
        • 2011-02-15
        • 1970-01-01
        • 2013-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多