这是我先前有关规范模式的增强问题 - 如何动态组合条件?.
我正在尝试将OnSaleSpecificationForBook
方法变成通用的。原因是音频CD逻辑也需要类似的规范,而且Book
和AudioCD
都实现了ISellingItem
接口。
规范
public class OnSaleSpecificationForBook : Specification<Book>
{
public override bool IsSatisfiedBy(Book product)
{
return product.IsOnSale;
}
}
我尝试创建如下的通用方法,但它会抛出以下错误:
找不到'T'类型或命名空间名称
带编译错误的代码
public class OnSaleSpecification : Specification<T>
{
public override bool IsSatisfiedBy(T item)
{
return item.IsOnSale;
}
}
问题
- 这个错误的原因是什么?
- 我们如何使这个方法变成通用的?
注意:我正在使用 .Net 4.0。但我想知道是否与 .Net 2.0 相比需要进行任何差异处理。
概述
public interface ISellingItem
{
bool IsOnSale { get; set; }
double Price { get; set; }
}
public abstract class Specification<T>
{
public abstract bool IsSatisfiedBy(T obj);
}
客户端
class Program
{
static void Main(string[] args)
{
List<Book> list = new List<Book>();
Book p1 = new Book(false, 99);
Book p2 = new Book(true, 99);
Book p3 = new Book(true, 101);
list.Add(p1);
list.Add(p2);
list.Add(p3);
var specification = new OnSaleSpecificationForBook();
List<Book> selectedList =
ProductFilterHelper.GetProductsUisngDynamicFilters(list, specification);
}
}
public static class ProductFilterHelper
{
public static List<Book> GetProductsUisngDynamicFilters(List<Book> productList, Specification<Book> productSpecification)
{
return productList.Where(p => productSpecification.IsSatisfiedBy(p))
.ToList();
}
}
实体
public class Book : ISellingItem
{
public bool IsOnSale { get; set; }
public double Price { get; set; }
public Book(bool isOnSale, double price)
{
this.Price = price;
this.IsOnSale = isOnSale;
}
}
public class AudioCD : ISellingItem
{
public bool IsOnSale { get; set; }
public double Price { get; set; }
public AudioCD(bool isOnSale, double price)
{
this.Price = price;
this.IsOnSale = isOnSale;
}
}