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!
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…