T4 (текстовый Шаблонный Инструментарий Преобразования) . T4 является генератором кода, встроенным прямо в Visual Studio
Многие ответы говорят, что вы не можете. Они неверны. Есть много способов сделать это без использования оператора приведения.
Метод № 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();
}
}
Вы не можете, но если вам приходится делать это много, вы можете определить вспомогательный помощник:
private IAInterface, который {get {return (IAInterface) this; }}
Всякий раз, когда вы хотите вызвать метод интерфейса, который был реализован явно, вы можете использовать that.method ()
вместо ((IAInterface) this) .method ()
.
Вы не можете просто удалить "IAInterface". из сигнатуры метода?
public class AImplementation : IAInterface
{
public void AInterfaceMethod()
{
}
void AnotherMethod()
{
this.AInterfaceMethod();
}
}