Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...