C# 接口作用的深入理解

黄舟
Libérer: 2017-02-17 11:06:35
original
1493 Les gens l'ont consulté

原文地址:http://www.php.cn/

假设我们公司有两种程序员:VB程序员,指的是用VB写程序的程序员,用clsVBProgramer这个类表示;Delphi程序员指的是用Delphi写程序的程序员,用clsDelphiProgramer这个类来表示。每个类都有一个WriteCode()方法。定义如下:

class clsVBProgramer()
{
....
WriteCode()
{
     //用VB语言写代码;
}
....
}

class clsDelphiProgramer()
{
....
WriteCode()
{
    //用Delphi语言写代码;
}
   ....
}
Copier après la connexion


现在公司来了一个项目,要求派某个程序员写一个程序。

class clsProject()
{
....
WritePrograme(clsVBProgramer programer)//用VB写代码
{
    programer.WriteCode();
}
WritePrograme(clsDelphiProgramer programer)//重载方法,用Delphi写代码
{
    programer.WriteCode();
}
......
}
Copier après la connexion


在主程序中我们可以这样写:

main()
{
   clsProject proj=new clsProject;
   //如果需要用VB写代码
   clsVBProgramer programer1=new clsVBProgramer;
   proj.WritePrograme(programer1);
   //如果需要用Delphi写代码
   clsDelphiProgramer programer2=new clsDelphiProgramer;
   proj.WritePrograme(programer2);
}
Copier après la connexion

但是如果这时公司又来了一个C#程序员,我们怎么改这段程序,使它能够实现用C#写程序的功能呢?我们需要增加一个新类clsCSharpProgramer,同时在此clsProject这个类中要再次重载WritePrograme(clsCSharpProgramer programer)方法。这下麻烦多了。如果还有C程序员,C++程序员,JAVA程序员呢。麻烦大了!

但是如果改用接口,就完全不一样了:
首先声明一个程序员接口:

interface IProgramer()
{
WriteCode();
}
然后声明两个类,并实现IProgramer接口:
class clsVBProgramer():IProgramer
{
....
WriteCode()
{
     //用VB语言写代码;
}
....
}
Copier après la connexion
class clsDelphiProgramer():IProgramer
{
....
WriteCode()
{
    //用Delphi语言写代码;
}
   ....
}
Copier après la connexion

对clsProject这个类进行一下修改:

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);   
}
Copier après la connexion


如果再有C#,C,C++,JAVA这样的程序员添加进来的话,我们只需把它们相关的类加进来,然后在main()中稍做修改就OK了。扩充性特别好!

另外我们如果把clsProject这个类封成一个组件,那么当我们的用户需要要扩充功能的时候,我们只需要在外部做很小的修改就能实现,可以说根本就用不着改动我们已经封好组件!是不是很方便,很强大!


 以上就是C#  接口作用的深入理解的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!