[英]How to call explicit interface implementation methods internally without explicit casting?
如果我有
public class AImplementation:IAInterface
{
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
((IAInterface)this).AInterfaceMethod();
}
}
如何在没有显式转换的情况下从AnotherMethod()
调用AInterfaceMethod()
?
许多答案说你不能。 他们是不正确的。 有很多方法可以在不使用强制转换运算符的情况下执行此操作。
技术#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();
}
}
还有另一种方式(这是 Eric's Technique #2 的衍生,如果接口没有实现,也应该给出编译时错误)
IAInterface AsIAInterface
{
get { return this; }
}
你不能,但如果你必须做很多事情,你可以定义一个方便的助手:
private IAInterface that { get { return (IAInterface)this; } }
每当您想调用显式实现的接口方法时,您都可以使用that.method()
而不是((IAInterface)this).method()
。
另一种方式(不是最好的):
(this ?? default(IAInterface)).AInterfaceMethod();
你不能删除“IAInterface”吗? 从方法签名?
public class AImplementation : IAInterface
{
public void AInterfaceMethod()
{
}
void AnotherMethod()
{
this.AInterfaceMethod();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.