zoukankan      html  css  js  c++  java
  • c#继承中的函数调用

    首先看下面的代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    using System;
     
    namespace Test
    {
        public class Base
        {
            public void Print()
            {
                Console.WriteLine(Operate(8, 4));
            }
     
            protected virtual int Operate(int x, int y)
            {
                return x + y;
            }
        }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    namespace Test
    {
        public class OnceChild : Base
        {
            protected override int Operate(int x, int y)
            {
                return x - y;
            }
        }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    namespace Test
    {
        public class TwiceChild : OnceChild
        {
            protected override int Operate(int x, int y)
            {
                return x * y;
            }
        }
    }
    1
    2
    3
    4
    5
    6
    namespace Test
    {
        public class ThirdChild : TwiceChild
        {
        }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    namespace Test
    {
        public class ForthChild : ThirdChild
        {
            protected new int Operate(int x, int y)
            {
                return x / y;
            }
        }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                Base b = null;
                b = new Base();
                b.Print();
                b = new OnceChild();
                b.Print();
                b = new TwiceChild();
                b.Print();
                b = new ThirdChild();
                b.Print();
                b = new ForthChild();
                b.Print();
            }
        }
    }

    看结果:



    从结果中可以看出:使用override重写之后,调用的函数是派生的最远的那个函数,使用new重写则是调用new之前的派生的最远的函数,即把new看做没有重写似的。

  • 相关阅读:
    抽象类
    继承
    面向对象的静态属性,类方法,静态方法
    查找linux系统下的端口被占用进程的两种方法 【转】
    awk学习
    【转】借助LVS+Keepalived实现负载均衡
    ORA-28001: the password has expired解决方法
    ORACLE的还原表空间UNDO写满磁盘空间,解决该问题的具体步骤
    Oracle控制文件多路复用以及Oracle备份重建控制文件
    RedHat6.1通过配置yum server安装软件包
  • 原文地址:https://www.cnblogs.com/rr163/p/4186688.html
Copyright © 2011-2022 走看看