Problem with C # interface with functional area

I have an interface as shown below:

public interface IInterface { void Open(); void Open(bool flag); void Open(bool flag, bool otherFlag); } 

Now, when implementing the interface, I have the following:

 public class IClass : IInterface { void IInterface.Open() { Open(false, false); } void IInterface.Open(bool flag) { Open(flag, false); } void IInterface.Open(bool flag, bool otherFlag) { //Do some stuff } } 

Now the problem that I am facing is that in the first two function bodies in IClass I cannot call the third function. I get an error message:

The name "Open" does not exist in the current context.

Ok, so I implement the interface explicitly (due to the requirement of another team in the organization), and then I get the "Open" problem. I can remove the explicit IInterface from the three public methods, and then I can successfully compile, even with other methods (not listed here) implemented explicitly, but I'm not sure what the consequences of this are.

Is there a way to call the third method when explicitly implementing interface methods?

Thanks!

+4
source share
4 answers

Explicit implementations require the use of an interface type reference directly, even inside an implementation class:

  void IInterface.Open() { (this as IInterface).Open(false, false); } void IInterface.Open(bool flag) { (this as IInterface).Open(flag, false); } 

Another way to preserve an explicit implementation is to delegate calls to a private method:

  private void Open(bool flag, bool otherFlag) { // Do some stuff. } 

Now your calls will be matched with this method:

  void IInterface.Open() { Open(false, false); } void IInterface.Open(bool flag) { Open(flag, false); } void IInterface.Open(bool flag, bool otherFlag) { Open(true, true); } 

Also note that your class name goes against the convention, removes the I prefix.

+7
source

You can do:

 ((IInterface)this).Open(false, false); 

One thing you can consider is to do other methods of extending the overloads on IInterface instead of re-implementing them each time:

 public static void Open(this IInterface iface, bool flag) { iface.Open(flag, false); } 
+3
source

Just make sure that you treat this object explicitly as an interface by pronouncing it first:

 void IInterface.Open(bool flag) { ((IInterface)this).Open(flag, false); } 
+1
source
 void IInterface.Open() { (this as IInterface).Open(false, false); } 
+1
source

Source: https://habr.com/ru/post/1487234/


All Articles