簡體   English   中英

如何在沒有顯式轉換的情況下在內部調用顯式接口實現方法?

[英]How to call explicit interface implementation methods internally without explicit casting?

如果我有

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

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

如何在沒有顯式轉換的情況下從AnotherMethod()調用AInterfaceMethod()

許多答案說你不能。 他們是不正確的。 有很多方法可以在不使用強制轉換運算符的情況下執行此操作。

技術#1:使用“as”運算符而不是強制轉換運算符。

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

技術#2:通過局部變量使用隱式轉換。

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

技巧#3:寫一個擴展方法:

static class Extensions
{
    public static void DoIt(this IAInterface ia)
    {
        ia.AInterfaceMethod(); // no cast here!
    }
}
...
void AnotherMethod()   
{      
    this.DoIt();  // no cast here either!
}

技巧#4:介紹一個幫手:

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

你可以引入一個輔助私有屬性:

private IAInterface IAInterface => this;

void IAInterface.AInterfaceMethod()
{
}

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

試過這個,它有效......

public class AImplementation : IAInterface
{
    IAInterface IAInterface;

    public AImplementation() {
        IAInterface = (IAInterface)this;
    }

    void IAInterface.AInterfaceMethod()
    {
    }

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

還有另一種方式(這是 Eric's Technique #2 的衍生,如果接口沒有實現,也應該給出編譯時錯誤)

     IAInterface AsIAInterface
     {
        get { return this; }
     }

你不能,但如果你必須做很多事情,你可以定義一個方便的助手:

private IAInterface that { get { return (IAInterface)this; } }

每當您想調用顯式實現的接口方法時,您都可以使用that.method()而不是((IAInterface)this).method()

另一種方式(不是最好的):

(this ?? default(IAInterface)).AInterfaceMethod();

你不能刪除“IAInterface”嗎? 從方法簽名?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM