简体   繁体   English

实现多个泛型类型的泛型接口-如何共享方法实现?

[英]Generic interface implementing multiple generic types - how to share a method implementation?

Let's say I have the following interface 假设我有以下界面

public interface IFilter<T>
{
    IEnumerable<T> ApplyFilter(IEnumerable<T> list);
}

And a specific implementation like this: 像这样的具体实现:

public class PetFilter: IFilter<Dog>, IFilter<Cat>
{
    public IEnumerable<Dog> ApplyFilter(IEnumerable<Dog> list)
    {
         return ApplyFilter<Dog>(list);
    }

    public IEnumerable<Cat> ApplyFilter(IEnumerable<Cat> list)
    {
         return ApplyFilter<Cat>(list);
    }

    private IEnumerable<T> ApplyFilter<T>(IEnumerable<T> list)
    {
         // do the work here
    }
}

Is there any way to avoid having to implement separate methods for both Dog and Cat, given that they share the same implementation? 假设它们共享相同的实现,是否有任何方法可以避免对Dog和Cat分别实现单独的方法?

Yes, given that Dog and Cat both inherit from a common base class or implement a common interface like eg IAnimal . 是的,因为DogCat都继承自通用基类或实现了通用接口,例如IAnimal Then for instance: 然后例如:

private IEnumerable<T> ApplyFilter(IEnumerable<T> list)
where T:IAnimal
{
     // do the work here
}

In other words, if Cat and Dog share the filtering logic, it surely refers to a common base. 换句话说,如果CatDog共享过滤逻辑,则它肯定是指一个共同的基础。

Yes and no. 是的,没有。 When you're using generics without any constraints the compiler would have no way of knowing of how to operate on the different classes (even if they were somehow related). 当您使用没有任何约束的泛型时,编译器将无法知道如何对不同的类进行操作(即使它们之间存在某种联系)。 Think for example how would the compiler know that ApplyFilter would work on both the Cat and the Dog classes? 例如,考虑编译器如何知道ApplyFilter在Cat和Dog类上都可以工作? To it Dog and Cat are completely separate things. 狗和猫完全是分开的。

However considering that both of your classes inherit from the same base class you can then operate on them through their common base class (or interface), but your PetFilter class would need to be generic as well. 但是,考虑到两个类都继承自同一个基类,则可以通过它们的公共基类(或接口)对其进行操作,但是您的PetFilter类也需要是通用的。

public abstract class Pet
{
}

public class Dog : Pet
{
}

public class Cat : Pet
{

}

Below is a generic PetFilter class, it inherits IFilter, and even though IFilter doesn't have a generic constraint, you can add one to the PetFilter class. 下面是一个通用的PetFilter类,它继承了IFilter,即使IFilter没有通用的约束,您也可以在PetFilter类中添加一个。

public class PetFilter<T> : IFilter<T> where T : Pet
{
    public IEnumerable<T> ApplyFilter(IEnumerable<T> list)
    {
        throw new NotImplementedException();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM