分享

C# 实例:重写(override)

 ontheroad96j47 2021-11-08

1、重写(override):子类中为满足自己的需要来重复定义某个方法的不同实现,需要用 override 关键字,被重写的方法必须是虚方法,用的是 virtual 关键字。它的特点是(三个相同):

  • 相同的方法名

  • 相同的参数列表

  • 相同的返回值

如:父类中的定义:

public virtual void EatFood()
{
Console.WriteLine("Animal吃东西");
}

子类中的定义:

public override void EatFood()
{
Console.WriteLine("Cat吃东西");
//base.EatFood();
}

小提示:经常有童鞋问重载和重写的区别,而且网络上把这两个的区别作为 C# 做常考的面试题之一。实际上这两个概念完全没有关系,仅仅都带有一个"重"字。他们没有在一起比较的意义,仅仅分辨它们不同的定义就好了。

3、虚方法:即为基类中定义的允许在派生类中重写的方法,使用virtual关键字定义。如:

public virtual void EatFood()
{
    
Console.WriteLine("Animal吃东西");
}

注意:虚方法也可以被直接调用。如:

Animal a = new Animal();
a
.EatFood();

执行输出结果为:

Animal吃东西

完整代码:

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;
namespace WindowsFormsApp4{ public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) {
}
private void button1_Click(object sender, EventArgs e) { test2 t2 = new test2(); t2.EatFood();
test1 t1 = new test1();//虚方法也可以被直接调用 t1.EatFood(); } }
// 对于类来说,如果你没有写访问修饰符,那么是internal的,只有程序集内部可以访问! //对于类的成员(字段, 属性, 方法等),如果你没有写访问修饰符,那么是private的! class test1 { public virtual void EatFood() //父类中的定义:基类中定义的允许在派生类中重写的方法,使用virtual关键字定义 { MessageBox.Show("Animal吃东西"); }
} partial class test2 : test1 { public override void EatFood() // 子类中的定义:子类中为满足自己的需要来重复定义某个方法的不同实现 { MessageBox.Show("Cat吃东西"); //base.EatFood(); } }
}


运行结果:

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多