[英]Default Interface Methods in C# 8
请考虑以下代码示例:
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团队的说法:
决策:Made 2017-04-11:运行I2.M,这是运行时明确最具体的覆盖。
我不确定在重写的界面上是否存在关键字“new”?应该是正确的行为?
如果您需要从源代码编译它,可以从以下网址下载源代码: https : //github.com/alugili/Default-Interface-Methods-CSharp-8
是的,这是因为new
关键字实际上隐藏了父类型的派生类型实现,因为它之前的类也是完全相同的行为,我们称之为Shadowing概念 。
所以输出会是55,你有类型的引用IPlayer
的Player
对象和ILimitedPlayer
的Attack
方法是从隐藏IPlayer
,因为的new
关键词在它的签名
我想说如果没有C#8编译器,你可以得到一个“很好的猜测”。 我们在这里基本上是:
public interface IPlayer {
// method 1
int Attack(int amount);
}
public interface IPowerPlayer : IPlayer {
// no methods, only provides implementation
}
public interface ILimitedPlayer : IPlayer {
// method 2, in question also provides implementation
new int Attack(int amount);
}
所以我们有2个接口方法(具有相同的签名),并且一些接口( IPowerPlayer
和ILimitedPlayer
)提供这些方法的实现。 我们可以在Player
类本身中提供实现来实现类似的功能:
public class Player : IPowerPlayer, ILimitedPlayer {
int IPlayer.Attack(int amount) {
return amount + 50;
}
int ILimitedPlayer.Attack(int amount) {
return amount + 10;
}
}
然后从问题输出中运行代码:
55
55
15
而且我认为为什么会相对清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.