题
受 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,这不太理想。
我在这里错过了什么吗?
解决方案
如果做得正确的话,它会起作用。cfeduke 的解决方案有效。但是,您不必 IPrimaryKey
接口通用,事实上,你根本不必改变你原来的定义:
public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey
{
return source(obj => obj.ID == id);
}
其他提示
编辑: 康拉德的解决方案更好,因为它简单得多。下面的解决方案有效,但仅在类似于 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);
由于泛型无法遵循继承模式,因此这是行不通的。IE。IQueryable<SimpleObj> 不在 IQueryable<IPrimaryKey> 的继承树中
不隶属于 StackOverflow