C # explicit implementation of interfaces

Source: Internet
Author: User

We are familiar with implementing interfaces in C #, But we generally use implicit implementations. How can we use explicit implementations and when can we use explicit implementations? See the following example:

In the preceding example, both interface A and interface B have a testmethod method, whose signatures are the same, but the returned results have different types. Testclass implements both interface A and interface B. If the above example uses implicit implementation, it is impossible to compile it. Error message: Type 'leleapplication4. testclass' already defines a member called 'testmethod' with the same parameter types. In this case, explicit interfaces are required. Which of the following is true?CodeThe implicit implementation of interface A, while explicit implementation of interface B.

 

     Interface  A {  Int  Testmethod ();}  Interface  B {  String  Testmethod ();} Class  Testclass: a, B {  Public   Int  Testmethod (){  Return   10  ;}  String  B. testmethod (){  Return  Testmethod (). tostring ();}} 

Here is another example. If we define a class, it implements the ienumerable <t> interface. Let's take a look at the definition of the ienumerable <t> interface and find that it inherits the ienumerable interface.

Public InterfaceIenumerable <OutT>: Ienumerable {ienumerator<T>Getenumerator ();}

The ienumerable interface is defined:

 
Public InterfaceIenumerable {ienumerator getenumerator ();}

It can be seen that to implement the ienumerable <t> interface, two getenumerator methods are required, and one of them must be explicit:

ClassTestcontainer <t>: ienumerable <t>{PublicIenumerator <t>Getenumerator (){Throw NewNotimplementedexception ();} system. Collections. ienumerator system. Collections. ienumerable. getenumerator (){Throw NewNotimplementedexception ();}}

In summary, in general, we can only implement implicit interfaces, but when two interfaces contain methods with the same signature, we must implement them explicitly.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.