我的代碼中有太多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