一个类可以从多个接口中派生出来,当一个类从定义了相同方法的两个或多个接口中派生时,你有两种选择:第一种是将两个接口方法引导到同一种方法实现中,第二种是提供不同的方法实现(利用显示实现)
interface
IMyInterface
... {
void Method1();
}
interface IMyOtherInterface
... {
void Method1();
}
class MyClass:IMyInterface,IMyOtherInterface
... {
IMyInterface 成员#region IMyInterface 成员
public void Method1()
...{
Console.WriteLine("Call MyClass Method1");
}
#endregion
IMyInterface 成员#region IMyInterface 成员
void IMyInterface.Method1()
...{
Console.WriteLine("显示Call IMyInterface MyClass Method1");
}
#endregion
IMyOtherInterface 成员#region IMyOtherInterface 成员
void IMyOtherInterface.Method1()
...{
Console.WriteLine("显示Call IMyOtherInterface IMyInterface MyClass Method1");
}
#endregion
class Program
...{
static void Main(string[] args)
...{
IMyInterface obj1 = new MyClass();
obj1.Method1();
IMyOtherInterface obj2 = new MyClass();
obj2.Method1();
MyClass obj3 = new MyClass();
obj3.Method1();
}
}
... {
void Method1();
}
interface IMyOtherInterface
... {
void Method1();
}
class MyClass:IMyInterface,IMyOtherInterface
... {
IMyInterface 成员#region IMyInterface 成员
public void Method1()
...{
Console.WriteLine("Call MyClass Method1");
}
#endregion
IMyInterface 成员#region IMyInterface 成员
void IMyInterface.Method1()
...{
Console.WriteLine("显示Call IMyInterface MyClass Method1");
}
#endregion
IMyOtherInterface 成员#region IMyOtherInterface 成员
void IMyOtherInterface.Method1()
...{
Console.WriteLine("显示Call IMyOtherInterface IMyInterface MyClass Method1");
}
#endregion
class Program
...{
static void Main(string[] args)
...{
IMyInterface obj1 = new MyClass();
obj1.Method1();
IMyOtherInterface obj2 = new MyClass();
obj2.Method1();
MyClass obj3 = new MyClass();
obj3.Method1();
}
}
得到的结果为
显示Call IMyInterface MyClass Method1
显示Call IMyOtherInterfaceMyClass Method1
Call MyClass Method1
如果你想同时使用显示接口实现并将实现从一个接口引导到另一个,你需要使用this引用来查询目标接口然后委托调用:
class
MyClass:IMyInterface,IMyOtherInterface
... {
IMyInterface 成员#region IMyInterface 成员
public void Method1()
...{
Console.WriteLine("Call MyClass Method1");
}
#endregion
IMyInterface 成员#region IMyInterface 成员
void IMyInterface.Method1()
...{
Console.WriteLine("显示Call IMyInterface MyClass Method1");
}
#endregion
IMyOtherInterface 成员#region IMyOtherInterface 成员
void IMyOtherInterface.Method1()
...{
IMyInterface myinterface = this;
myinterface.Method1();
}
#endregion
}
... {
IMyInterface 成员#region IMyInterface 成员
public void Method1()
...{
Console.WriteLine("Call MyClass Method1");
}
#endregion
IMyInterface 成员#region IMyInterface 成员
void IMyInterface.Method1()
...{
Console.WriteLine("显示Call IMyInterface MyClass Method1");
}
#endregion
IMyOtherInterface 成员#region IMyOtherInterface 成员
void IMyOtherInterface.Method1()
...{
IMyInterface myinterface = this;
myinterface.Method1();
}
#endregion
}
为了避免混淆最好不要使用一个类继承具有同样接口方法的接口,写完这些东西感觉自己有点像孔乙己,呵呵!