简体   繁体   中英

How to have public methods implemented from interface?

I have following interface

interface ITest
{
  void TestVoid();
}

class A : ITest
{
   public void ITest.TestVoid() //will not work
   {
     Conole.WriteLine("Done");
   }

   public void TestVoid() //without name of interface, it works
   {
     Conole.WriteLine("Done");
   }
}

Second question: Is that correct that interface only contains signature of members but never the implementation?

First method is explicit implementation. This allows you to implement interface, without showing this method outside of your class. Also, you cant have visibility modifier on explicit implementation.

Second method is normal (implicit) implementation, where you implement interface AND create public method.

More : Implicit and Explicit Interface Implementations , C#: Interfaces - Implicit and Explicit implementation

For your second question : This is exacly what interface is. It only tells you, what method, properties or events are available on the object. Not how they are implemented.

The first is called Explicit implementation and should not have any access specifier, Explicit interfaces can also be used to hide the details of an interface that the class developer considers private. Second one is implicit implementation. It must have public as access specifier.

this link is really helpful to understand it. http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx

I answer to your second question: yes, it's correct.
Interface declare a sort of contract you must work with if you implement that interface.
An interface simply (and only) declare what you MUST writein your classes if you implement those interfaces.

You need to implement the interface like.

class A : ITest {
}.   

You can implement ITests methods explicitly with ITest. Prefix

Or implicitly as public methods

If they are explicit the the way to access them is as such.

ITest a = new A();

Otherwise.
A a = new A();

An interface never has an implementation,
A class method always does unless it's marked as abstract - then the derived class has the implementatio n

The first is called explicit implementation, it will work like this:

interface ITest
{
  void TestVoid();
}
class A : ITest
{
   public static void Main()
   {
       A a1 = new A();
       ITest a2 = new A();
       a1.TestVoid(); // won't work
       a2.TestVoid(); // will work
   }
   public void ITest.TestVoid()
   {
     Conole.WriteLine("Done");
   }
}

Interface cannot ever contain implemenations, only signatures.

第二个是好的,所以你可以使用它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM