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?!


动漫人物
浏览 123回答 2
2回答

温温酱

我说您可以对“没有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;    }}然后从问题输出运行代码:555515而且我认为原因很清楚。
打开App,查看更多内容
随时随地看视频慕课网APP