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

  • 相关阅读:
    设计模式学习笔记-观察者模式
    谈C#中的Delegate
    EF 增删改查 泛型方法、类
    什么是表达式树,它与表达式、委托有什么区别?
    查询出各个学科的前3名的同学信息的Sql
    row_number() OVER(PARTITION BY)函数介绍
    Asp.net WebApi 项目示例(增删改查)
    ASP.NET WebAPI从入门
    .net中的Queue和Stack
    Replication--数据库镜像阻塞复制日志读取器的解决的办法
  • 原文地址:https://www.cnblogs.com/larson/p/3683527.html
Copyright © 2011-2022 走看看