Original address: //m.sbmmt.com/
Suppose there are two types of programmers in our company: VB programmers, referring to Programmers who write programs in VB are represented by the class clsVBProgramer; Delphi programmers refer to programmers who write programs in Delphi, represented by the class clsDelphiProgramer. Every class has a WriteCode() method. The definition is as follows:
##
class clsVBProgramer() { .... WriteCode() { //用VB语言写代码; } .... } class clsDelphiProgramer() { .... WriteCode() { //用Delphi语言写代码; } .... }
Now the company has a project, Ask a programmer to write a program.
##class clsProject()
{
....
WritePrograme(clsVBProgramer programer)//用VB写代码
{
programer.WriteCode();
}
WritePrograme(clsDelphiProgramer programer)//重载方法,用Delphi写代码
{
programer.WriteCode();
}
......
}
In the main program we can do this Write:
##main()
{
clsProject proj=new clsProject;
//如果需要用VB写代码
clsVBProgramer programer1=new clsVBProgramer;
proj.WritePrograme(programer1);
//如果需要用Delphi写代码
clsDelphiProgramer programer2=new clsDelphiProgramer;
proj.WritePrograme(programer2);
}
First declare a programmer interface:
interface IProgramer() { WriteCode(); } 然后声明两个类,并实现IProgramer接口: class clsVBProgramer():IProgramer { .... WriteCode() { //用VB语言写代码; } .... }
class clsDelphiProgramer():IProgramer { .... WriteCode() { //用Delphi语言写代码; } .... }
Modify the clsProject class:
class clsProject() { .... WritePrograme(IProgramer programer) { programer.WriteCode();//写代码 } ...... } main() { clsProject proj=new clsProject; IProgramer programer; //如果需要用VB写代码 programer=new clsVBProgramer; proj.WritePrograme(programer); //如果需要用Delphi写代码 programer=new clsDelphiProgramer; proj.WritePrograme(programer); }
If programmers like C#, C, C++, and JAVA are added, we only need to add their related classes, and then in main() It's OK with a little modification. The scalability is particularly good!
The above is the in-depth understanding of the role of C# interface. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!