现在我的代码是这样的:(简化!)
public static IQueryable<T> ListedProducts<T,V>(this IQueryable<T> collection)
where T : ProductCollection<V>
where V: Product
{
return collection.Where(x => x.Listed == true);
}
要使用它,我必须像这样定义两种类型:
SomeCollection.ListedProducts<BikeCollection,BikeProduct>()
这就是我希望的样子:
我希望能够写一些像这样的东西:
public static IQueryable<T> ListedProducts<T<V>>(this IQueryable<T<V>> collection)
where T : ProductCollection<V>
{
return collection.Where(x => x.Listed == true);
}
我只需要写的地方:
SomeCollection.ListedProducts()
我认为这是可能的,因为“SomeCollection”包含通用 ListedProducts 方法的两种类型。
希望我的问题足够清楚并且有解决方案:)
更新
我的代码的设置方式似乎有很多错误,所以这里有一些类(简化的)
产品系列
public class ProductCollection<T> where T : Product
{
public int Id { get; set; }
public string CollectionName { get; set; }
public virtual ICollection<T> Products { get; set; }
public bool Listed { get; set; }
}
产品系列
public class BikeCollection : ProductCollection<BikeProduct>
{
//Bike specific properties
}
请您参考如下方法:
编辑:根据您最近的更新,我建议如下:
建议:更改ProductCollection<T>以便它实现 IEnumerable<T> :
public class ProductCollection<T> : IEnumerable<T>
where T : Product
{
public int Id { get; set; }
public string CollectionName { get; set; }
public virtual ICollection<T> Products { get; set; }
public bool Listed { get; set; }
// This is all it takes to implement IEnumerable<T>
public IEnumerator<T> GetEnumerator() { return this.Products.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator() { return this.Products.GetEnumerator(); }
}
然后,您可以通过以下方式更改您的扩展:
public static IEnumerable<T> ListedProducts<T>(this IEnumerable<T> collection)
where T : Product
{
return collection.Where(x => x.Listed == true);
}
这允许您执行以下操作:
// WHERE BikeCollection : ProductCollection<BikeProduct>
// AND BikeProduct : Product
var someCollection = new BikeCollection();
// What you want
var listedBikes1 = someCollection.ListedProducts();
// Another way you can do it, if ProductCollection<T> : IEnumerable<T>
var listedBikes2 =
from product in someCollection
where product.Listed
select product;
