C#函数重载

关于C#的重载
重载有两种方式,第一种方式new
这种方式是在派生类创建一个新的元素,通过新的元素进行多态
virtual和override
对原来的数据进行重载
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;d 

namespace test继承
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        public class Animal {
            public virtual string Eat() {
                return "我是动物";
            }
        }

        public class Dog :Animal{
            public override string Eat() {
                return "我是狗";
            }
        }
        public class Cat : Animal
        {
            public new string Eat()
            {
                return "我是猫";
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Animal a = new Dog();
            Console.WriteLine("virtual和override的重载");
            Dog c = new Dog();
            Console.WriteLine(a.Eat());
            Console.WriteLine(c.Eat());
            Animal b = new Cat();
            Console.WriteLine("new的重载");
            Cat d = new Cat();
            Console.WriteLine(d.Eat());
            Console.WriteLine(b.Eat());

        }
    }
}



结果:       Animal a = new Dog();
            Console.WriteLine("virtual和override的重载");
            Dog c = new Dog();
            Console.WriteLine(a.Eat());//override的上转型
            Console.WriteLine(c.Eat());
            virtual和override的重载
            我是狗
            我是狗
            Animal b = new Cat();
            Console.WriteLine("new的重载");
            Cat d = new Cat();
            Console.WriteLine(d.Eat());
            Console.WriteLine(b.Eat());//new的上转型
            new的重载
            我是猫
            我是动物 

 

posted @ 2019-03-06 19:52  大眼侠  阅读(1849)  评论(0编辑  收藏  举报