【发布时间】:2018-04-16 15:12:39
【问题描述】:
考虑以下代码示例:
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 团队的说法:
Decision: Made 2017-04-11: Runs I2.M, which is the unambiguously most specific override at runtime.
由于被覆盖的界面上的关键字“new”,我在这里不确定?正确的行为应该是什么?
如果您需要从源代码编译它,您可以从以下位置下载源代码: https://github.com/alugili/Default-Interface-Methods-CSharp-8
【问题讨论】:
-
"我可以编译代码但不能执行它!"为什么你不能执行它? IMO,输出将是
55 -
我认为这与
IPowerPlayerAttack方法显式实现IPlayer方法,而ILimitedPlayerAttack方法隐式实现它有关。或者可能是因为它使用new关键字遮蔽了它。这可能是两者的结合。 -
@BassamAlugili 这搞砸了。我不觉得它应该编译允许你有两个方法,相同的名称,不同的功能,在每个接口上。
-
@CamiloTerevinto 执行不起作用我已经构建了分支并启动了该功能。一切工作正常,编译,智能等,除了执行时出现错误 --> 接口中不允许使用方法
-
也许您应该等待 C#8 编译器?
标签: c# c#-8.0 default-interface-member