C#抽象类和协变

时间:2012-10-18 06:04:40

标签: c# refactoring ooad

我有一些像这样的代码:

class DataFilter
{
    List<Animal> animals=null;
    public function1(string TypeOfData)
    {
        if(TypeOfData=="cat"){//get cats from database and do something}
        else if(TypeOfData=="dog")
        {//get dogs & do something}
    }
}
class Animal
{}
class Cat:Animal
{}
class Dog:Animal
{}

如果我重用DataFilter类:

 class CatFilter:DataFilter
 {
 }

如何重用列表动物属性???

如何重构它以将function1拆分为不同的类

2 个答案:

答案 0 :(得分:2)

 List<Animal> animals = new List<Animal>() { new Dog(), new Cat() };
 foreach (var animal in animals)
      animal.DoSomething();

-

class Animal
{ public virtual void DoSomething() { } }

class Cat : Animal
{ public override void DoSomething() { Console.WriteLine("CAT"); } }

class Dog : Animal
{ public override void DoSomething() { Console.WriteLine("DOG"); } }

<强> - 编辑 -

我仍然无法理解你真正想要的是什么。但是看到关键字filter让我想到了

var groupedAnimals = animals.GroupBy(a => a.GetType())
                         .Select(g => new { Type = g.Key, Animals = g.ToList() })
                         .ToList();

var cats = animals.OfType<Cat>().ToList();

答案 1 :(得分:1)

您可以在设计中使用概念多态,例如:

class DataFilter
{
    List<Animal> animals = new List<Animal>() { new Dog(), new Cat() };

    public function1()
    {
        foreach (var animal in animals)
            animal.Do();
    }
}

abstract class Animal
{
    public abstract void Do();
}

class Cat: Animal
{
    public override void Do() {}  
}

class Dog: Animal
{
    public override void Do() {}
}