gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:13:39 25 4
gpt4 key购买 nike

这是对我之前关于规范模式的问题的改进 - 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com