欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#继承中的函数调用实例

程序员文章站 2023-12-14 14:54:22
本文实例讲述了c#继承中的函数调用方法,分享给大家供大家参考。具体分析如下: 首先看下面的代码: 复制代码 代码如下:using system;   na...

本文实例讲述了c#继承中的函数调用方法,分享给大家供大家参考。具体分析如下:

首先看下面的代码:

复制代码 代码如下:
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;
        }
    }
}

namespace test
{
    public class oncechild : base
    {
        protected override int operate(int x, int y)
        {
            return x - y;
        }
    }
}

namespace test
{
    public class twicechild : oncechild
    {
        protected override int operate(int x, int y)
        {
            return x * y;
        }
    }
}

namespace test
{
    public class thirdchild : twicechild
    {
    }
}

namespace test
{
    public class forthchild : thirdchild
    {
        protected new int operate(int x, int y)
        {
            return x / y;
        }
    }
}

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();
        }
    }
}


运行结果为:
12
4
32
32
32

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

希望本文所述对大家的c#程序设计有所帮助。

上一篇:

下一篇: