简体   繁体   中英

How to call explicit interface implementation methods internally without explicit casting?

If I have

public class AImplementation:IAInterface
{
   void IAInterface.AInterfaceMethod()
   {
   }

   void AnotherMethod()
   {
      ((IAInterface)this).AInterfaceMethod();
   }
}

How to call AInterfaceMethod() from AnotherMethod() without explicit casting?

A number of answers say that you cannot. They are incorrect. There are lots of ways of doing this without using the cast operator.

Technique #1: Use "as" operator instead of cast operator.

void AnotherMethod()   
{      
    (this as IAInterface).AInterfaceMethod();  // no cast here
}

Technique #2: use an implicit conversion via a local variable.

void AnotherMethod()   
{      
    IAInterface ia = this;
    ia.AInterfaceMethod();  // no cast here either
}

Technique #3: write an extension method:

static class Extensions
{
    public static void DoIt(this IAInterface ia)
    {
        ia.AInterfaceMethod(); // no cast here!
    }
}
...
void AnotherMethod()   
{      
    this.DoIt();  // no cast here either!
}

Technique #4: Introduce a helper:

private IAInterface AsIA => this;
void AnotherMethod()   
{      
    this.AsIA.IAInterfaceMethod();  // no casts here!
}

You can introduce a helper private property:

private IAInterface IAInterface => this;

void IAInterface.AInterfaceMethod()
{
}

void AnotherMethod()
{
   IAInterface.AInterfaceMethod();
}

Tried this and it works...

public class AImplementation : IAInterface
{
    IAInterface IAInterface;

    public AImplementation() {
        IAInterface = (IAInterface)this;
    }

    void IAInterface.AInterfaceMethod()
    {
    }

    void AnotherMethod()
    {
       IAInterface.AInterfaceMethod();
    }
}

And yet another way (which is a spin off of Eric's Technique #2 and also should give a compile time error if the interface is not implemented)

     IAInterface AsIAInterface
     {
        get { return this; }
     }

You can't, but if you have to do it a lot you could define a convenience helper:

private IAInterface that { get { return (IAInterface)this; } }

Whenever you want to call an interface method that was implemented explicitly you can use that.method() instead of ((IAInterface)this).method() .

另一种方式(不是最好的):

(this ?? default(IAInterface)).AInterfaceMethod();

Can't you just remove the "IAInterface." from the method signature?

public class AImplementation : IAInterface
{
   public void AInterfaceMethod()
   {
   }

   void AnotherMethod()
   {
      this.AInterfaceMethod();
   }
}

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