c# - 将具体类型的泛型集合转换为基类型的集合

标签 c# linq generics ienumerable

我有许多实现特定接口(interface) (ISearchable) 的类,我想从一个静态方法,但我不确定如何在不进行中间集合的情况下转换它。

代码很简单,其中一个域对象的实现如下:

public class account : ISearchable
{
    public static IEnumerable<ISearchable> Search(string keyword)
    {
        // ORMVendorCollection<T> implements IQueryable<T>
        ORMVendorCollection<account> results = /* linq query */

        // this works if I change the return type to IEnumerable<account>
        // but it uglifies client code a fair bit
        return results.AsEnumerable<account>();

        // this doesn't work, but it's what I'd like to achieve            
        return results.AsEnumerable<ISearchable>(); 
    }
}

客户端代码,理想情况下如下所示:

public static IEnumerable<ISearchable> Search(string keyword)
{
    return account.Search(keyword)
        .Concat<ISearchable>(order.Search(keyword))
        .Concat<ISearchable>(otherDomainClass.Search(keyword));
}

最佳答案

使用 Cast<T>扩展方法

return results.Cast<ISearchable>();

关于c# - 将具体类型的泛型集合转换为基类型的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3686987/

相关文章:

java - 确保类型参数正确

c# - 委托(delegate) System.Action<dynamic,int> 不接受 `1' 参数

c# - 无法插入数据库

c# - ListView Tapped 删除数据模板 Xamarin.Forms 上的按钮背景颜色

c# - 使用 LINQ 按索引连接

LINQ 加入多个条件?

performance - 在LINQ表达式中如何获得性能更好的FirstOrDefault?

android - 在kotlin中findviewbuid作为T

java - 这是在 Java 中使用泛型的正确方法吗?

c# - 不允许使用 ASP.NET Core 2.2 WebAPI 405 方法