2009-12-08 42 views
25

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

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

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

如何調用從AnotherMethod()AInterfaceMethod()沒有明確的鑄造?

+0

演員的問題是什麼? – adrianm 2009-12-08 18:39:26

+0

當我發現這種語言功能時,我只是皺眉。但是,在實現像ICloneable這樣的接口時非常有用。 – 2009-12-08 21:06:35

+2

爲什麼不這樣做呢?將代碼從顯式接口方法移動到「正常」方法。然後讓所有方法(包括顯式接口方法)調用該方法。 – adrianm 2009-12-10 07:16:26

回答

-3

難道你不能只是刪除「IAInterface」。從方法簽名?

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

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

然後它不會是一個明確的實現。 – 2009-12-08 18:58:38

8

嘗試這樣做,它的工作原理...

public class AImplementation : IAInterface 
{ 
    IAInterface IAInterface; 

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

    void IAInterface.AInterfaceMethod() 
    { 
    } 

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

你不能,但如果你有做了很多,你可以定義一個快捷的幫助:

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

無論何時您想調用明確實現的接口方法,都可以使用that.method()而不是((IAInterface)this).method()

+1

值得注意的是,這裏不需要明確的轉換(因爲存在從'this'到'IAInterface'的實現的隱式轉換)。 – 2009-12-08 20:17:18

5

您可以引入一個輔助的私有財產:

private IAInterface IAInterface { get { return this; } } 

void IAInterface.AInterfaceMethod() 
{ 
} 

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

許多的答案說,你不能。他們是不正確的。有很多方法可以在不使用演員的情況下做到這一點。

技術#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() { return this; } 
void AnotherMethod() 
{  
    this.AsIA().IAInterfaceMethod(); // no casts here! 
} 
+5

爲了迂腐,他沒有要求不要使用「演員」,他要求「沒有明確演員」,我認爲,一般來說,操作符「as」將被視爲「明確演員」(不知道如果這在語言規範定義方面是正確的,或者在這種情況下這個問題甚至沒有意義)。 – 2009-12-08 20:37:26

+1

那麼,鑄造操作符的語義和as操作符的語義是完全不同的,所以混淆它們是一個邏輯錯誤。有關詳細信息,請參閱http://beta.blogs.msdn.com/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx。 – 2009-12-08 21:06:31

+6

我知道這已經很老了,但今天我偶然發現了這個問題。我認爲「最好」的方式是隱含的演員嗎?這爲我正確的代碼提供了最佳編譯時保護?如果我使用cast或「as」操作(在這種情況下實際上沒有任何意義,因爲該對象本應該首先實現接口),所以我冒着嘗試投射到無效接口的風險,運行時錯誤。如果我嘗試隱式轉換爲類沒有實現的接口,我得到一個編譯時錯誤,而且更好。 – julealgon 2013-05-24 14:14:47

0

又一種方式(未最好):

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

而另一種方式(這是從埃裏克的技術#2,如果接口不實現,也應該給編譯時間錯誤)

 IAInterface AsIAInterface 
    { 
     get { return this; } 
    } 
相關問題