-5

i have some code like this:

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
{}

if i reuse the DataFilter class:

 class CatFilter:DataFilter
 {
 }

how to reuse list animals property???

how to refactor it to split the function1 into different class

Scott 混合理论
  • 2,263
  • 8
  • 34
  • 59

2 Answers2

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"); } }

--EDIT--

I still can not understand what you really want. But seeing the keyword filter makes me think

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

or

var cats = animals.OfType<Cat>().ToList();
L.B
  • 114,136
  • 19
  • 178
  • 224
1

You can use concept polymorphism into your design, example:

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() {}
}
cuongle
  • 74,024
  • 28
  • 151
  • 206