許多的答案說,你不能。他們是不正確的。有很多方法可以在不使用演員的情況下做到這一點。
技術#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!
}
演員的問題是什麼? – adrianm 2009-12-08 18:39:26
當我發現這種語言功能時,我只是皺眉。但是,在實現像ICloneable這樣的接口時非常有用。 – 2009-12-08 21:06:35
爲什麼不這樣做呢?將代碼從顯式接口方法移動到「正常」方法。然後讓所有方法(包括顯式接口方法)調用該方法。 – adrianm 2009-12-10 07:16:26