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拆分为不同的类
答案 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() {}
}