这里我想用C#做什么:
unknownClass handle;
if(blabla)
handle = new A();
else
handle = new B();
handle.CommonMethod();
显然,A类和B类都有方法CommonMethod
。
我该怎么做?
答案 0 :(得分:7)
让A
和B
都实现一个具有方法CommonMethod
的接口。使用该界面代替unknownClass
。
答案 1 :(得分:2)
您可以使用界面执行此作业:
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();
答案 2 :(得分:1)
如前所述,您应该使用接口。 例如:
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();
答案 3 :(得分:1)
接口或公共基类应始终是此处的首选选项。如果需要,我实际上会为每个具体类型引入一个接口和包装类。当没有其他选择时,:
dynamic obj = ...
obj.CommonMethod(); // this is a hack
但是:先做其他事。就像我说的:如果你不能自己编辑对象,那么包装类型会更好:
IFoo obj;
...
obj = new BarWrapper(new Bar());
...
obj.CommonMethod();