当你实现多个接口或单一接口时(C#允许多接口继承)和抽象成员时,如何来避免拥有矛盾名字的现象呢?先看下面的代码: ie: //第一个接口的声明 public interface Iinterface1{ void xyz();} //第二个接口的声明 public interface Iinterface2{ void xyz();} //抽象类的声明 public abstract class MyAbstract{ public abstract void xyz(); } //定义一个衍生类来继承接口和抽象类 class Derived:Iinterface1,Iinterface2,MyAbstract{} //在Derived类中为继承的抽象类和接口成员提供函数定义 //接口1的xyz()方法 void IInterface1.xyz() { Console.WriteLine("调用接口1的xyz()方法. \n"); } //接口2的xyz()方法 void IInterface2.xyz(){ Console.WriteLine("调用接口2的xyz()方法. \n");} //抽象类的xyz()方法 public override void xyz() { Console.WriteLine("调用抽象类的xyz()方法. \n"); } 看到这里,大家都应该明白怎样实现了。 接下来就为整个Derived类定义入口点并实例化它。 ie: //实例化Derived对象,声明接口变量并指定Derived类对象给接口 static void Main(string[] args) { Derived derived = new Derived(); IInterface1 interface1 = new Derived(); IInterface2 interface2 = new Derived();} //你应该可以获得抽象类和接口的成员函数了,并且可以避免名字的矛盾冲突。 derived.xyz(); interface1.xyz(); interface2.xyz(); 运行结果如下: 调用接口1的xyz()方法. 调用接口2的xyz()方法. 调用抽象类的xyz()方法. 最后给出全部代码的实现方式: using System;namespace Example{ public interface IInterface1 { void xyz(); } public interface IInterface2 { void xyz(); } public abstract class MyAbstractClass { public abstract void xyz(); } class Derived : MyAbstractClass,IInterface1,IInterface2 { [STAThread] private static void Main(string[] args) { Derived derived = new Derived(); IInterface1 interface1 = new Derived(); IInterface2 interface2 = new Derived(); derived.xyz(); interface1.xyz(); interface2.xyz(); Console.WriteLine("请按回车键退出."); Console.ReadLine(); } void IInterface1.xyz() { Console.WriteLine("调用接口1的xyz()方法. \n"); } void IInterface2.xyz() { Console.WriteLine("调用接口2的xyz()方法. \n"); } public override void xyz() { Console.WriteLine("调用抽象类的xyz()方法. \n"); } }} 结论: 当它们拥有相同名字的时候,一个用户可以获取两个接口和抽象的方法,从而避免名字相同而冲突的问题。 Enjoy!

评论