[英]How to make this generic method?
這是對我之前關於規范模式的問題的增強 - 如何動態組合條件? 。
我試圖使OnSaleSpecificationForBook
方法成為通用方法。 原因是AudioCD邏輯也需要類似的規范, 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;
}
}
在編譯器知道它是一個ISellingItem
之前,您需要指定泛型參數的類型正在實現的ISellingItem
。 您可以使用where T: ISellingItem
子句執行此操作:
public class OnSaleSpecification<T> : Specification<T> where T : ISellingItem
{
public override bool IsSatisfiedBy(T item)
{
return item.IsOnSale;
}
}
您的OnSaleSpecification類需要定義泛型參數T並將其約束為ISellingItem
public class OnSaleSpecification<T> : Specification<T> where T : ISellingItem
{
public override bool IsSatisfiedBy(T item)
{
return item.IsOnSale;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.