在C#中實現介面大家都很熟悉,但一般我們用的都是隱性實現,那麼我們怎麼使用顯性實現,以及什麼時候用顯性實現呢?請看下面的例子:
在上面的例子中,在介面A和介面B中都有一個TestMethod方法,它們的簽名相同,只是返回的結果類型不同。TestClass既要實現介面A,又要實現介面B。如果向上面的例子那樣都採用隱性實現,是不可能通過編譯的。錯誤資訊為:Type 'ConsoleApplication4.TestClass' already defines a member called 'TestMethod' with the same parameter types。所以在這種情況下,就要使用顯性實現介面了。下面是正確的代碼,我們對介面A隱性實現,而對介面B顯性實現。
interface A { int TestMethod(); } interface B { string TestMethod(); } class TestClass : A, B { public int TestMethod() { return 10; } string B.TestMethod() { return TestMethod().ToString(); } }
再舉一個例子。假如我們定義一個類,它實現 IEnumerable<T> 介面。來看一下IEnumerable<T> 介面的定義,發現它又繼承了IEnumerable介面。
public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); }
而IEnumerable介面的定義為:
public interface IEnumerable { IEnumerator GetEnumerator(); }
可見,如果要實現IEnumerable<T> 介面,就要實現兩個GetEnumerator方法,而其中的一個就必然為顯性的實現:
class TestContainer<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }
總結,一般的情況下,我們都可以只用隱性實現介面,但當兩個介面含有相同簽名的方法時,我們就必須採用顯性實現了。