开发者

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

If I have

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

   void AnotherMethod()
   {
开发者_C百科      ((IAInterface)this).AInterfaceMethod();
   }
}

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


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().


Yet another way (not best):

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜