我有许多实现特定接口(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/