zoukankan      html  css  js  c++  java
  • Interface的多层继承

    我有一段如下代码,定义一个接口iInterface,cBase实现iInterface,cChild继承cBase,UML为

    image

    预期是想要cBase.F()的执行逻辑,同时需要cChild的返回值,所以FF预期的输出

    image

       1:  namespace ConsoleApplication1
       2:  {
       3:      class Program
       4:      {
       5:          static void Main(string[] args)
       6:          {
       7:              iInterface inf = new cChild();
       8:              FF(inf);
       9:   
      10:              Console.ReadLine();
      11:          }
      12:          static public void FF(iInterface inf)
      13:          {
      14:              Console.WriteLine(inf.F());
      15:          }
      16:      }
      17:   
      18:      public interface iInterface
      19:      {
      20:          string F();
      21:      }
      22:      public class cBase : iInterface
      23:      {
      24:          public  string F()
      25:          {
      26:              Console.WriteLine("base.F1");
      27:              return "this is base";
      28:          }
      29:      }
      30:      public class cChild : cBase
      31:      {
      32:          public string F()
      33:          {
      34:              base.F();
      35:              return "this is child";
      36:          }
      37:      }
      38:  }

    但是实际的结果是只能call到cBase的F函数,输出”this is base

    image

    原因是我们定义的inf类型为iInterface,同时赋值的对象类型为cChild,但是cChild是没有实现iInterface的(继承至实现了接口的class也是不行的)。

    实际运行时,inf向上找到了cBase有实现iInterface,所以调用了它的实现。

    想达到预期的结果,可以将cChild也实现iInterface,如下:

       1:  public class cChild : cBase, iInterface
       2:      {
       3:          public string F()
       4:          {
       5:              base.F();
       6:              return "this is child";
       7:          }
       8:      }

    修改后的UML为

    image

    输出结果为:

    image

  • 相关阅读:
    为什么qt成为c++界面编程的第一选择 老夏课堂
    升级 package.json 内所有包的版本号
    小米 pro 双硬盘设置引导盘
    react 疑问集锦
    jmeter 基础使用
    vmware ubuntu 看不到网卡或连接不到网络
    如何在 Windows 11 使用旧的(或完整的)右键菜单
    hbuilder x 连接夜神模拟器
    当初为什么报 软件工程 这个专业?
    sparky 一个趋势图的JavaScript插件
  • 原文地址:https://www.cnblogs.com/larson/p/3683527.html
Copyright © 2011-2022 走看看