这两者之间有什么区别(这是IFoo<string>)。做()和这个。在下面的代码中做()?



我经常发现,就像在ArrayMarkupExtension.cs中一样,人们做的选角在我看来是微不足道的。

考虑简化版本如下。

以下代码中的(this as IFoo<string>).Do()和仅this.Do()之间有什么区别?

interface IFoo
{
object Do();
}
interface IFoo<out T> : IFoo
{
new T Do();
}
class Something : IFoo<string>
{
public string Do()
{
return this.GetType().Name;
}
object IFoo.Do()
{
//return this.Do();
return (this as IFoo<string>).Do();
}
}

我刚刚理解了。

  • (this as IFoo<string>).Do();调用string IFoo<string>.Do() => "IFoo<string>.Do()";(如果可用(。否则,它调用public string Do() => "Do()";

  • this.Do();只能调用public string Do() => "Do()";

完整的代码:

interface IFoo
{
object Do();
}
interface IFoo<out T> : IFoo
{
new T Do();
}
class Something : IFoo<string>
{
string IFoo<string>.Do() => "IFoo<string>.Do()";
public string Do() => "Do()";
//object IFoo.Do() => (this as IFoo<string>).Do();
object IFoo.Do() => this.Do();
}
class Program
{
static void Main()
{
IFoo<string> x = new Something();
Console.WriteLine(x.Do());
}
}

相关内容

最新更新