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

来源:互联网 发布:香港中文大学 知乎 编辑:程序博客网 时间:2024/05/22 06:19
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();
        }
    }
}

原创粉丝点击