C# 介面的顯性實現

來源:互聯網
上載者:User

在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();        }    }

總結,一般的情況下,我們都可以只用隱性實現介面,但當兩個介面含有相同簽名的方法時,我們就必須採用顯性實現了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.