考虑以下代码示例:
public interface IPlayer
{
int Attack(int amount);
}
public interface IPowerPlayer: IPlayer
{
int IPlayer.Attack(int amount)
{
return amount + 50;
}
}
public interface ILimitedPlayer: IPlayer
{
new int Attack(int amount)
{
return amount + 10;
}
}
public class Player : IPowerPlayer, ILimitedPlayer
{
}
使用代码:
IPlayer player = new Player();
Console.WriteLine(player.Attack(5)); // Output 55, --> im not sure from this output. I can compile the code but not execute it!
IPowerPlayer powerPlayer = new Player();
Console.WriteLine(powerPlayer.Attack(5)); // Output 55
ILimitedPlayer limitedPlayer = new Player();
Console.WriteLine(limitedPlayer.Attack(5)); // Output 15
我的问题在于这段代码:
Console.WriteLine(player.Attack(5)); // Output 55
问题是:输出应该是15还是55?!
根据.NET团队: 决定:2017-04-11做出:运行I2.M,在运行时这是最具体的重载。 因为覆盖接口上有关键字“new”,我不确定这里应该怎么做才是正确的行为?
如果您需要从源代码进行编译,可以从以下位置下载源代码: https://github.com/alugili/Default-Interface-Methods-CSharp-8
55
。 - Camilo TerevintoIPowerPlayer
的Attack
方法显式实现了IPlayer
方法有关,而ILimitedPlayer
的Attack
方法是隐式实现的。或者可能是因为它使用了new
关键字来隐藏它。这可能是两者的结合体。 - Zohar Peled