如何在内部调用显式接口实现方法没有明确的铸造?接口、明确、方法、如何在

2023-09-03 02:22:18 作者:浅色、记忆づ

如果我有

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

   void AnotherMethod()
   {
      ((IAInterface)this).AInterfaceMethod();
   }
}

如何调 AInterfaceMethod() AnotherMethod()没有明确的铸造?

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

推荐答案

若干答案说你不能。它们是不正确的。有很多这样做的方式,而无需使用转换运算符。

A number of answers say that you cannot. They are incorrect. There are lots of ways of doing this without using the cast operator.

技术#1:使用为运营商,而不是转换运算符

Technique #1: Use "as" operator instead of cast operator.

void AnotherMethod()   
{      
    (this as IAInterface).AInterfaceMethod();  // no cast here
}

技术#2:通过一个局部变量使用隐式转换

Technique #2: use an implicit conversion via a local variable.

void AnotherMethod()   
{      
    IAInterface ia = this;
    ia.AInterfaceMethod();  // no cast here either
}

技术#3:写一个扩展方法:

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

技术#4:介绍一个帮手:

Technique #4: Introduce a helper:

private IAInterface AsIA() { return this; }
void AnotherMethod()   
{      
    this.AsIA().IAInterfaceMethod();  // no casts here!
}