Interface的多层继承

时间:2025-01-10 14:06:39

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

Interface的多层继承

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

Interface的多层继承

   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:  }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

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

Interface的多层继承

原因是我们定义的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为

Interface的多层继承

输出结果为:

Interface的多层继承