Wiele odpowiedzi, że nie można. Są niepoprawne. Istnieje wiele sposobów na to, bez korzystania z operatora obsady.
Technika # 1: Użyj operatora "as" zamiast operatora cast.
void AnotherMethod()
{
(this as IAInterface).AInterfaceMethod(); // no cast here
}
Technika # 2: użyj niejawnej konwersji za pomocą zmiennej lokalnej.
void AnotherMethod()
{
IAInterface ia = this;
ia.AInterfaceMethod(); // no cast here either
}
Technika # 3: napisać metodę rozszerzenia:
static class Extensions
{
public static void DoIt(this IAInterface ia)
{
ia.AInterfaceMethod(); // no cast here!
}
}
...
void AnotherMethod()
{
this.DoIt(); // no cast here either!
}
Technika # 4: wprowadzenie pomocnika:
private IAInterface AsIA() { return this; }
void AnotherMethod()
{
this.AsIA().IAInterfaceMethod(); // no casts here!
}
Jaki jest problem z obsadą? – adrianm
Właśnie zmarszczyłem brwi, gdy odkryłem tę funkcję języka. Jest to bardzo przydatne przy implementowaniu niektórych interfejsów, takich jak ICloneable. –
Dlaczego nie zrobić tego na odwrót? Przenieś kod z jawnej metody interfejsu do "normalnej" metody. Następnie pozwól, aby wszystkie metody (w tym jawna metoda interfejsu) wywoływały tę metodę. – adrianm