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看做没有重写似的。

  • 相关阅读:
    设计模式之笔记--工厂方法模式(Factory Method)
    dmesg命令
    jumpserver2.3.0社区开源版
    container偶尔宕掉问题的解决记录
    sshd服务的白名单和黑名单
    /proc/sysrq-trigger文件
    ansible定义主机清单
    简述Etcd、Lvs、HAProxy
    ES6语法 let、const、for...of循环、展开运算符、ES6箭头函数、箭头函数和this、模板字面量、解构、对象字面量简写法、默认参数函数、super 和 extends、Object.assign()
    axios 将post请求时把对象obj数据转为formdata
  • 原文地址:https://www.cnblogs.com/rr163/p/4186688.html
Copyright © 2011-2022 走看看