2016-12-30 17 views
6

爲什麼在實現類的方法名稱之前包含接口引用是否有任何原因?例如,假設您有一個ReportService:IReportService和一個GetReport(int reportId)方法。我正在審查一些代碼,另一個開發者實現這樣的方法ReportService的:爲什麼接口引用會包含在實現類的方法名稱之前?

Report IReportService.GetReport(int reportId) 
{ 
    //implementation 
} 

我以前從未見過這樣的服務實現。它有什麼用途?

+0

可以肯定的是,如果實現類具有相同簽名的方法,您可以區分它。 – Tobias

+0

顯式接口實現不允許使用可見性修飾符。我很肯定你只是在你的問題中輸入錯誤,所以繼續編輯它。如果您認爲我錯了,如果您認爲「公共」真的存在,請隨時恢復,但那時您無法編譯。 – hvd

回答

12

這被稱爲「顯式接口實現」。其原因可能是例如命名衝突。

考慮接口IEnumerableIEnumerable<T>。一個聲明瞭一個非泛型方法

IEnumerator GetEnumerator(); 

,另一個是通用的一個:

IEnumerator<T> GetEnumerator(); 

在C#它不允許有兩個方法與只在有返回類型不同,相同的名稱。所以,如果你實現這兩個接口,你需要聲明一個方法明確:

public class MyEnumerable<T> : IEnumerable, IEnumerable<T> 
{ 
    public IEnumerator<T> GetEnumerator() 
    { 
     ... // return an enumerator 
    } 

    // Note: no access modifiers allowed for explicit declaration 
    IEnumerator IEnumerable.GetEnumerator() 
    { 
     return GetEnumerator(); // call the generic method 
    } 
} 

明確實現的接口方法不能對實例變量被稱爲:

MyEnumerable<int> test = new MyEnumerable<int>(); 
var enumerator = test.GetEnumerator(); // will always call the generic method. 

如果要調用非-generic方法,您需要投testIEnumerable

((IEnumerable)test).GetEnumerator(); // calls the non-generic method 

這似乎也是爲什麼在顯式實現中不允許訪問修飾符(如publicprivate)的原因:它在類型上不可見。

+0

你也可以從接口明確實現非公開實現的東西(這可能是另一個原因)。 –

+0

@ M.kazemAkhgary確實。值得補充的是,如果一個公共類實現了一個內部接口,並且內部接口聲明瞭一個帶有內部返回類型的方法,那麼公共類*不能*實現它作爲公共方法,它*必須*求助於顯式接口實現。 – hvd

相關問題