人生是一场不能存盘的RPG,我只能尽量多搞几个Screenshot

June 5, 2007

为什么在派生类中再次实现一个Interface?

Filed under: .NET, C#

比如:
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:

Comments »

The URI to TrackBack this entry is: http://recordsome.blogsome.com/2007/06/05/p255/trackback/

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Anti-spam measure: please retype the above text into the box provided.






















Get free blog up and running in minutes with Blogsome
Theme designed by Hadley Wickham