假如在實(shí)現(xiàn)多個(gè)接口時(shí),接口中包含有相同和函數(shù),必須要顯式地實(shí)現(xiàn)各個(gè)函數(shù)(有一個(gè)可以隱式實(shí)現(xiàn)),而且在以后調(diào)用的時(shí)候也必須通過(guò)接口調(diào)用。說(shuō)不太清,還是看代碼吧:
假如有兩個(gè)接口IReadalbe和IStorable,都含有Read();
interface IStorable
{
void Read( );
}
interface IReadable
{
int Read();
}
然后,我們有個(gè)類(lèi)使用這兩個(gè)接口:
class Test : IStorable, IReadable
{
public int Read()
{
Console.WriteLine("Which one?");
return 1;
}
//void IStorable.Read()
//{
// Console.WriteLine("IStorable?");
//}
}
假如不取消注釋?zhuān)敲创a無(wú)法通過(guò)編譯(沒(méi)有實(shí)現(xiàn)全部接口)。取消注釋后,int Read()表示為實(shí)現(xiàn)IReadable接口。寫(xiě)代碼測(cè)試:
Test t = new Test();
t.Read(); //輸出為 Which one?
IStorable a = t;
a.Read(); //輸出為 IStorable
IReadable b = t;
b.Read(); //輸出為 Which one?
看起來(lái)似乎沒(méi)有什么問(wèn)題,假如我們?cè)亠@示地實(shí)現(xiàn)IReadable的Read(),即在Test類(lèi)里面再添加如下代碼:
int IReadable.Read()
{
Console.WriteLine("IReadable");
return 1;
}
再測(cè)試:
Test t = new Test();
t.Read(); //輸出為 Which one?
IStorable a = t;
a.Read(); //輸出為 IStorable
IReadable b = t;
b.Read(); //輸出為 IReadable
這里看起來(lái)我們的確能夠通過(guò)接口調(diào)用我們實(shí)現(xiàn)的函數(shù),但是此時(shí)的t.Read()就不知道該算什么了。它似乎不是任何一個(gè)接口的實(shí)現(xiàn),而且我們可以隨意更改它的返回類(lèi)型,看起來(lái)似乎它又成了一個(gè)獨(dú)立函數(shù)?在第一次測(cè)試中,IReadable認(rèn)為它是其實(shí)現(xiàn)并調(diào)用,可是在第二次測(cè)試中,IReadable發(fā)現(xiàn)了自己的專(zhuān)門(mén)實(shí)現(xiàn)后就不在調(diào)用它了。結(jié)果這個(gè)Read()就成了不是任何接口的實(shí)現(xiàn),但它卻和接口提供的函數(shù)同名! 或者說(shuō)Test類(lèi)的Read()實(shí)現(xiàn)了3個(gè)接口?
如果兩個(gè)接口都是提供void Read(),那么我們只要實(shí)現(xiàn)在Test類(lèi)里實(shí)現(xiàn)void Read()就可以算是同時(shí)實(shí)現(xiàn)了兩個(gè)接口,不過(guò)我們?nèi)匀豢梢燥@式地為兩個(gè)接口提供不同的實(shí)現(xiàn)函數(shù),那樣的話(huà),我們?nèi)匀豢梢栽俅嬖谝粋€(gè)與接口無(wú)關(guān)的同名函數(shù)。
此外,對(duì)于IReadable.Read()和IStorable.Read()都不能用pubic這類(lèi)modifiers來(lái)修飾,否則報(bào)錯(cuò)。
雖然看起來(lái)是很奇怪的一種實(shí)現(xiàn),而且也找不到什么實(shí)際的意義,不過(guò)既然發(fā)現(xiàn)了這個(gè)現(xiàn)象,先在此做個(gè)記錄,說(shuō)不定以后有新發(fā)現(xiàn)。
也希望有實(shí)際經(jīng)驗(yàn)的人說(shuō)說(shuō)實(shí)際項(xiàng)目中會(huì)不會(huì)有這種情況。