這裏我想用C#做的事:對未知類使用通用方法?
unknownClass handle;
if(blabla)
handle = new A();
else
handle = new B();
handle.CommonMethod();
顯然,類A和B都具有方法CommonMethod
。
我該怎麼做?
這裏我想用C#做的事:對未知類使用通用方法?
unknownClass handle;
if(blabla)
handle = new A();
else
handle = new B();
handle.CommonMethod();
顯然,類A和B都具有方法CommonMethod
。
我該怎麼做?
您可以使用接口這個工作:
interface ICommon
{
void CommonMethod();
}
public class A : ICommon
{
//implement CommonMethod
}
public class B : ICommon
{
//implement CommonMethod
}
則:
ICommon handle;
if(blabla)
handle = new A();
else
handle = new B();
handle.CommonMethod();
此解決方案可以通過使用工廠(工廠設計模式)來決定要創建哪個對象。 – srsyogesh
使A
和B
都有一個接口,該接口具有方法CommonMethod
。使用該接口代替unknownClass
。
如前所述,你應該使用的接口。 實施例:
public interface IBarking{
public void Barks();
}
public class Dog : IBarking{
//some specific dog properties
public void Barks(){
string sound = "Bark";
}
}
public class Wolf : IBarking{
//some specific wolf properties
public void Barks(){
string sound = "Woof";
}
}
//and your implementation here:
IBarking barkingAnimal;
if (isDog){
barkingAnimal = new Dog();
}
else {
barkingAnimal = new Wolf();
}
barkingAnimal.Barks();
的接口或常見基類應始終是這裏優選的選項。如果需要,我會爲每個具體類型引入一個接口和包裝類。當沒有其他選擇可能,雖然:
dynamic obj = ...
obj.CommonMethod(); // this is a hack
但是:做一切首位。就像我說的那樣:如果你不能自己編輯對象,包裝類型會更可取:
IFoo obj;
...
obj = new BarWrapper(new Bar());
...
obj.CommonMethod();
你是否有能力修改類A和B的實現?換句話說,它們不是你無法控制的某個圖書館的一部分? –