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

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

If I have

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

   void AnotherMethod()
   {
      ((IAInterface)this)         


        
相关标签:
7条回答
  • 2020-12-08 19:10

    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; }
         }
    
    0 讨论(0)
  • 2020-12-08 19:12

    Yet another way (not best):

    (this ?? default(IAInterface)).AInterfaceMethod();
    
    0 讨论(0)
  • 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!
    }
    
    0 讨论(0)
  • 2020-12-08 19:17

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

    0 讨论(0)
  • 2020-12-08 19:18

    You can introduce a helper private property:

    private IAInterface IAInterface => this;
    
    void IAInterface.AInterfaceMethod()
    {
    }
    
    void AnotherMethod()
    {
       IAInterface.AInterfaceMethod();
    }
    
    0 讨论(0)
  • 2020-12-08 19:20

    Tried this and it works...

    public class AImplementation : IAInterface
    {
        IAInterface IAInterface;
    
        public AImplementation() {
            IAInterface = (IAInterface)this;
        }
    
        void IAInterface.AInterfaceMethod()
        {
        }
    
        void AnotherMethod()
        {
           IAInterface.AInterfaceMethod();
        }
    }
    
    0 讨论(0)
提交回复
热议问题