为什么在派生类中再次实现一个Interface?
比如:
TemplateContorl实现了INameContainer,其派生类UserContorl又实现INameContainer.
INameContainer仅仅是一个marker interface,其用途也就是看一个class是否实现了此interface,
UserContorl就算不实现INameContainer,仍然可以cast为INameContainer.
又如:
StringCollection,实现了IList, ICollection, IEnumerable,而IList实现了ICollection, IEnumerable,
ICollection又实现了IEnumerable.
其目的在于可在StringCollection中显式实现这些Interface,对一些方法的参数类型进行强化:
public int IndexOf(string value);
int IList.IndexOf(object value)
{
return this.IndexOf((string) value);
}
以便在编译阶段发现问题.
考察如下代码:
interface ITest
{
void ShowMsg();
}
interface IITest:ITest
{
}
public class TestA : ITest
{
public void ShowMsg()
{
Console.WriteLine(”TestA:”);
}
void ITest.ShowMsg()
{
Console.WriteLine(”TestA:ITest”);
}
}
public class TestB :TestA, ITest
{
public void ShowMsg() //Complier warning,hides inherited member ‘TestA.ShowMsg()’
{
Console.WriteLine(”TestB:”);
}
void ITest.ShowMsg()
{
Console.WriteLine(”TestB:ITest”);
}
}
TestB test = new TestB();
test.ShowMsg();
(test as TestA).ShowMsg();
ITest itest = new TestB();
itest.ShowMsg();
输出:
TestB:
TestA:
TestB:ITest
如果去掉TestB对ITest的实现, (test as ITest).ShowMsg();将输出TestB:
