扩展方法不适用于接口

Kir*_*ein 6 .net c# extension-methods

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

我有这个界面;

IPrimaryKey
{
  int ID { get; }
}
Run Code Online (Sandbox Code Playgroud)

我有这种扩展方法

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

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

我在这里错过了什么吗?

Kon*_*lph 13

如果做得好,它可以工作.cfeduke的解决方案有效.但是,您不必使IPrimaryKey接口通用,事实上,您根本不必更改原始定义:

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