C# 是否对未知类使用泛型方法?
下面是我想用C做的事情:C# 是否对未知类使用泛型方法?,c#,methods,C#,Methods,下面是我想用C做的事情: unknownClass handle; if(blabla) handle = new A(); else handle = new B(); handle.CommonMethod(); 显然,类A和类B都有方法CommonMethod 我该怎么做呢?让A和B实现一个接口,该接口有一个方法CommonMethod。使用该接口代替unknownClass。您可以将该接口用于此作业: interface ICommon {
unknownClass handle;
if(blabla)
handle = new A();
else
handle = new B();
handle.CommonMethod();
显然,类A和类B都有方法CommonMethod
我该怎么做呢?让A和B实现一个接口,该接口有一个方法CommonMethod。使用该接口代替unknownClass。您可以将该接口用于此作业:
interface ICommon
{
void CommonMethod();
}
public class A : ICommon
{
//implement CommonMethod
}
public class B : ICommon
{
//implement CommonMethod
}
然后:
如前所述,您应该使用接口。 例如:
在这里,接口或公共基类应始终是首选选项。如果需要的话,我会为每种具体类型引入一个接口和包装器类。但是,如果没有其他选项,请执行以下操作: 但是:先做其他事情。就像我说的:如果您不能编辑对象本身,那么包装器类型更可取:
IFoo obj;
...
obj = new BarWrapper(new Bar());
...
obj.CommonMethod();
您是否有能力修改类A和类B的实现?换句话说,它们不是您无法控制的某个库的一部分?通过使用factory设计模式来决定要创建哪个对象,可以扩展此解决方案。
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();