C#用接口实现传递不同的类的多态
接口及类的定义
//定义接口,define interface
interface IAction
{
string Act();
}
/// <summary>
/// 类A继承接口,class a inherit interface IAction
/// </summary>
class InterfaceTest :IAction
{
public string Act()
{
return "this class a.Act";
}
}
/// <summary>
/// 类B继承接口,class a inherit interface IAction
/// </summary>
class Bclass : IAction
{
public string Act()
{
return "this class b.Act";
}
}
/// <summary>
/// 类C定义方法以IAction接口为参数,class C set the interface as parameter
/// </summary>
class Cclass
{
public string CallFun(IAction action)
{
return action.Act();
}
}
调用
//实例化类,instantiate
InterfaceTest aclass = new InterfaceTest();
Bclass bclass = new Bclass();
Cclass cclass = new Cclass();
//将类做参数传递调用各种的方法,use the class as parameter to call different functions
MessageBox.Show(cclass.CallFun(bclass)+"\n"+ cclass.CallFun(aclass));