0

我有一系列类型的集合,所有这些都派生自同一个基类,以及一组用于搜索每个类型的谓词,例如

public abstract class Animal { ... }    
public class Dog : Animal { ... }       
public class Cat : Animal { ... }

...
Func<Dog, bool> DogFinder = ...;
Func<Cat, bool> CatFinder = ...;
...

List<Dog> Dogs = GetDogs(DogFinder);
List<Cat> Cats = GetCats(CatFinder);

有没有办法可以避免每种类型的重复?

我的下一步是采用 Dogs、Cats 并转换为常见的“结果”类型并返回这些相当简单的集合,但我觉得中间的重复应该被排除在外,以便我添加更多类型的动物未来它将干净地扩展。

4

1 回答 1

0

您可以使用泛型来消除一些重复,例如:

List<TAnimal> GetAnimals<TAnimal>(Func<TAnimal, bool> predicate) : where TAnimal : Animal
{
  ...
}

然后你可以这样调用:

List<Dog> Dogs = GetAnimals(DogFinder);
List<Cat> Cats = GetAnimals(CatFinder);

您还可以重载方法(和谓词)以获取两个参数并返回基本类型的列表,如下所示:

List<Animal> GetAnimals(Func<TAnimal1, TAnimal2, bool> predicate) 
    : where TAnimal1 : Animal
    : where TAnimal2 : Animal
{
   ...
}

然后你可以用一个新的谓词把你的狗和猫放在一起:

Func<Dog, Cat, bool> DogAndCatFinder = ...;

得到你的清单是这样的:

List<Animal> DogsAndCats = GetAnimals(DogAndCatFinder);
于 2015-01-13T03:41:52.510 回答