[英]How to call explicit interface implementation methods internally without explicit casting?
If I have如果我有
public class AImplementation:IAInterface
{
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
((IAInterface)this).AInterfaceMethod();
}
}
How to call AInterfaceMethod()
from AnotherMethod()
without explicit casting?如何在没有显式转换的情况下从
AnotherMethod()
调用AInterfaceMethod()
?
A number of answers say that you cannot.许多答案说你不能。 They are incorrect.
他们是不正确的。 There are lots of ways of doing this without using the cast operator.
有很多方法可以在不使用强制转换运算符的情况下执行此操作。
Technique #1: Use "as" operator instead of cast operator.技术#1:使用“as”运算符而不是强制转换运算符。
void AnotherMethod()
{
(this as IAInterface).AInterfaceMethod(); // no cast here
}
Technique #2: use an implicit conversion via a local variable.技术#2:通过局部变量使用隐式转换。
void AnotherMethod()
{
IAInterface ia = this;
ia.AInterfaceMethod(); // no cast here either
}
Technique #3: write an extension method:技巧#3:写一个扩展方法:
static class Extensions
{
public static void DoIt(this IAInterface ia)
{
ia.AInterfaceMethod(); // no cast here!
}
}
...
void AnotherMethod()
{
this.DoIt(); // no cast here either!
}
Technique #4: Introduce a helper:技巧#4:介绍一个帮手:
private IAInterface AsIA => this;
void AnotherMethod()
{
this.AsIA.IAInterfaceMethod(); // no casts here!
}
You can introduce a helper private property:你可以引入一个辅助私有属性:
private IAInterface IAInterface => this;
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
Tried this and it works...试过这个,它有效......
public class AImplementation : IAInterface
{
IAInterface IAInterface;
public AImplementation() {
IAInterface = (IAInterface)this;
}
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
}
And yet another way (which is a spin off of Eric's Technique #2 and also should give a compile time error if the interface is not implemented)还有另一种方式(这是 Eric's Technique #2 的衍生,如果接口没有实现,也应该给出编译时错误)
IAInterface AsIAInterface
{
get { return this; }
}
You can't, but if you have to do it a lot you could define a convenience helper:你不能,但如果你必须做很多事情,你可以定义一个方便的助手:
private IAInterface that { get { return (IAInterface)this; } }
Whenever you want to call an interface method that was implemented explicitly you can use that.method()
instead of ((IAInterface)this).method()
.每当您想调用显式实现的接口方法时,您都可以使用
that.method()
而不是((IAInterface)this).method()
。
另一种方式(不是最好的):
(this ?? default(IAInterface)).AInterfaceMethod();
Can't you just remove the "IAInterface."你不能删除“IAInterface”吗? from the method signature?
从方法签名?
public class AImplementation : IAInterface
{
public void AInterfaceMethod()
{
}
void AnotherMethod()
{
this.AInterfaceMethod();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.