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

后端 未结 7 764
谎友^
谎友^ 2020-12-08 18:44

If I have

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

   void AnotherMethod()
   {
      ((IAInterface)this)         


        
7条回答
  •  情书的邮戳
    2020-12-08 19:14

    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!
    }
    

提交回复
热议问题