受 MVC 店面的启发,我正在从事的最新项目是使用 IQueryable 上的扩展方法来过滤结果。
我有这个界面;
IPrimaryKey
{
int ID { get; }
}
我有这个扩展方法
public static IPrimaryKey GetByID(this IQueryable<IPrimaryKey> source, int id)
{
return source(obj => obj.ID == id);
}
假设我有一个实现 IPrimaryKey 的类 SimpleObj。当我有 SimpleObj 的 IQueryable 时,GetByID 方法不存在,除非我明确地转换为 IPrimaryKey 的 IQueryable,这不太理想。
我是不是漏掉了什么?
最佳答案
如果操作得当,它会起作用。 cfeduke 的解决方案有效。但是,您不必使 IPrimaryKey
接口(interface)通用,事实上,您根本不必更改原始定义:
public static IPrimaryKey GetByID<T>(this IQueryable<T> source, int id) where T : IPrimaryKey
{
return source(obj => obj.ID == id);
}
关于c# - 扩展方法不适用于接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/82442/