接口的作用:规范,提高可扩展性,便于维护。
例子,
public interface IProgramer
{
void WriteCode();
}
class clsCSharpProgramer:IProgramer
{
public void WriteCode()//实现具体的writecode的方法
{
Console.Write("CSharp");
}
}
class clsVBProgramer : IProgramer
{
public void WriteCode()
{
Console.Write("VB");
}
}
public class clsProject
{
public void writeprograme(IProgramer programer)//提高可扩展性
{
programer.WriteCode();
}
}
static void Main()
{
clsProject proj = new clsProject();
IProgramer programmer1 = new clsCSharpProgramer();//提高可扩展性
IProgramer programmer2=new clsVBProgramer();
proj.writeprograme(programmer1);
proj.writeprograme(programmer2);
Console.ReadKey();
}
---------------------------如果不继承接口-------------------------
public class clsCSharpProgramer
{
public void WriteCode()
{
Console.Write("CSharp");
}
}
public class clsVBProgramer
{
public void WriteCode()
{
Console.Write("VB");
}
}
public class clsProject
{
public void writeprograme(clsCSharpProgramer cprogramer)
{
cprogramer.WriteCode();
}
public void writeprograme(clsVBProgramer vbprogramer)
{
vbprogramer.WriteCode();
}
}
static void Main()
{
clsProject proj = new clsProject();
clsCSharpProgramer cp = new clsCSharpProgramer();
proj.writeprograme(cp);
clsVBProgramer cv = new clsVBProgramer();
proj.writeprograme(cv);
Console.ReadKey();
}