Как вызывать явные методы реализации интерфейса внутри без явного литья?
Если у меня
public class AImplementation:IAInterface
{
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
((IAInterface)this).AInterfaceMethod();
}
}
Как вызвать AInterfaceMethod()
из AnotherMethod()
без явного литья?
Ответы
Ответ 1
Несколько ответов говорят, что вы не можете. Они неверны. Существует множество способов сделать это без использования оператора трансляции.
Техника № 1: вместо оператора трансляции используйте оператор "как".
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!
}
Ответ 2
Пробовал это, и он работает...
public class AImplementation : IAInterface
{
IAInterface IAInterface;
public AImplementation() {
IAInterface = (IAInterface)this;
}
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
}
Ответ 3
Вы можете ввести вспомогательную частную собственность:
private IAInterface IAInterface { get { return this; } }
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
Ответ 4
И еще один способ (который является оттиском Eric Technique # 2, а также должен давать ошибку времени компиляции, если интерфейс не реализован)
IAInterface AsIAInterface
{
get { return this; }
}
Ответ 5
Вы не можете, но если вам нужно это сделать, вы можете определить помощника удобства:
private IAInterface that { get { return (IAInterface)this; } }
Всякий раз, когда вы хотите вызвать метод интерфейса, который был реализован явно, вы можете использовать that.method()
вместо ((IAInterface)this).method()
.
Ответ 6
Еще один способ (не лучший):
(this ?? default(IAInterface)).AInterfaceMethod();
Ответ 7
Нельзя ли просто удалить "IAInterface". из подписи метода?
public class AImplementation : IAInterface
{
public void AInterfaceMethod()
{
}
void AnotherMethod()
{
this.AInterfaceMethod();
}
}