c# - 如何制作这个通用方法?

标签 c# generics

这是对我之前关于规范模式的问题的改进 - How to combine conditions dynamically? .

我正在尝试使 OnSaleSpecificationForBook 方法成为通用方法。原因是 AudioCD 逻辑也需要类似的规范,BookAudioCD 都实现了 ISellingItem 接口(interface)。

规范

public class OnSaleSpecificationForBook : Specification<Book>
{
    public override bool IsSatisfiedBy(Book product)
    {
        return product.IsOnSale;
    }
}

我试图创建一个如下所列的通用方法,但它抛出以下错误:

The type or namespace name 'T' could not be found

有编译错误的代码

public class OnSaleSpecification : Specification<T>
{
    public override bool IsSatisfiedBy(T item)
    {
        return item.IsOnSale;
    }
}

问题

  1. 这个错误的原因是什么?
  2. 我们怎样才能使这个方法通用?

注意:我使用的是 .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 之前,您需要指定泛型参数的类型正在实现什么。您可以使用 where T: ISellingItem 子句执行此操作:

public class OnSaleSpecification<T> : Specification<T> where T : ISellingItem
{
    public override bool IsSatisfiedBy(T item)
    {
        return item.IsOnSale;
    }
}

关于c# - 如何制作这个通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21437845/

相关文章:

Java:如何设计此类以具有可选泛型 ParameterType?

c# - 如何封装额外的字段?

c# - 使用 WPF 自定义控件库 (.NET Framework) 中普通 WPF 项目中的 App.xaml

c# - 以编程方式禁用在 xaml 中创建的样式触发器

c# - Windows Phone 列表框在平移时闪烁

c# - 如何在 64 位 .NET 进程中设置 MinWorkingSet 和 MaxWorkingSet?

返回类型有限的 C# 泛型

generics - 在 Rust 中实现 len() 函数的类型的通用较长函数

java - 使用 JPA 选择元组的好方法

java - 如何在java中使用引用自类型的抽象方法创建接口(interface)