如果我有
public class AImplementation:IAInterface
{
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
((IAInterface)this).AInterfaceMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
如何AInterfaceMethod()从AnotherMethod()没有明确的投射来打电话?
Eri*_*ert 69
一些答案说你做不到.他们是不正确的.如果不使用强制转换运算符,有很多方法可以做到这一点.
技术#1:使用"as"运算符而不是强制运算符.
void AnotherMethod()
{
(this as IAInterface).AInterfaceMethod(); // no cast here
}
Run Code Online (Sandbox Code Playgroud)
技术#2:通过局部变量使用隐式转换.
void AnotherMethod()
{
IAInterface ia = this;
ia.AInterfaceMethod(); // no cast here either
}
Run Code Online (Sandbox Code Playgroud)
技巧#3:编写扩展方法:
static class Extensions
{
public static void DoIt(this IAInterface ia)
{
ia.AInterfaceMethod(); // no cast here!
}
}
...
void AnotherMethod()
{
this.DoIt(); // no cast here either!
}
Run Code Online (Sandbox Code Playgroud)
技巧#4:介绍帮手:
private IAInterface AsIA => this;
void AnotherMethod()
{
this.AsIA.IAInterfaceMethod(); // no casts here!
}
Run Code Online (Sandbox Code Playgroud)
您可以介绍一个帮助私有财产:
private IAInterface IAInterface => this;
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
Run Code Online (Sandbox Code Playgroud)
试过这个,它的工作原理......
public class AImplementation : IAInterface
{
IAInterface IAInterface;
public AImplementation() {
IAInterface = (IAInterface)this;
}
void IAInterface.AInterfaceMethod()
{
}
void AnotherMethod()
{
IAInterface.AInterfaceMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14167 次 |
| 最近记录: |