c# - 扩展方法不适用于接口(interface)

标签 c# .net extension-methods

受 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/

相关文章:

c# - 如何在 GridView 单元格中呈现解码后的 HTML(即 <br>)

c# - LINQ:将 .Single() 转换为查询符号

c# - ConnectionString 中未指定 OLE DB 提供程序。 '供应商= SQLOLEDB;

c# - 在 Azure Service Fabric 服务中,在何处以及如何实例化 ServiceInitializationParameters?

c# - System.Web.Razor.dll 未复制到 bin 文件夹

.net - 使用.net API将音频实时流传输到android客户端的最佳方法是什么

c# - C#中的函数Socket.Select()在linux操作系统中使用epoll吗?

c# - ParameterInfo 是扩展方法参数?

c# - 如何在 C# 中的类上创建扩展方法?

c# - 无法将 lambda 表达式转换为类型 'string',因为它不是委托(delegate)类型