我的代码中有太多downcasts。在C++中,我可以使用模板来避免向下转换。但在C#中以下示例的最佳实现是什么?如何避免函数中太多downcasts
class Pet { bool mIsDog; }
class Dog : Pet // mIsDog = true
class Cat : Pet // mIsDog = false
class Owner //There are many different owner classes, may come from different dlls
{
private List<Food> mFoods;
private void FeedDog(Dog dog)
{
... //Use mFoods, which is invisible to dog
}
void HandlePet(Pet pet)
{
if(pet.mIsDog) //In c++ I can use templates to avoid downcasting
FeedDog((Dog)pet);
else
FeedCat((Cat)pet);
... //code handling general pet
while(pet.IsUnhappy())
{
if(pet.mIsDog) //In c++ I can use templates to avoid downcasting
PlayWithDog((Dog)pet);
else
PlayWithCat((Cat)pet);
}
... //a lot of code handling general pet or specific pet (cat or dog)
}
}
注意功能HandlePet有压痕的多层次非常复杂的逻辑,因此很难将其拆分成多个独立的功能。
,我不作BeFedWith或BePlayedWith宠物类中的虚函数的是,我可以有很多不同的用户类别,例如,BoyOwner,GirlOwner,WomanOwner,ManOwner,每一个都有自己的方式来养活的原因宠物。宠物是一个普通的类,被许多其他类使用,但所有者类只与宠物交互。另外,FeedDog等函数需要访问Owner类的私有成员。
是否有任何理由认为'Pet'不是带'Play'和'Feed'方法的抽象类? – 2013-04-24 15:06:14
您可以为您的Pet类添加一个抽象的BeFed(或类似命名)方法,并从您的所有者类中调用该方法,那么您不需要获取具体类,只需(现在是抽象的)'Pet'类就足够了。 (编辑:他说什么!) – 2013-04-24 15:07:25
在'Pet'中有'mIsDog'是一个非常非常糟糕的设计决定。 – 2013-04-24 15:08:37