1、重写(override):子类中为满足自己的需要来重复定义某个方法的不同实现,需要用 override 关键字,被重写的方法必须是虚方法,用的是 virtual 关键字。它的特点是(三个相同):
如:父类中的定义: public virtual void EatFood(){ Console.WriteLine("Animal吃东西"); } 子类中的定义: public override void EatFood(){ Console.WriteLine("Cat吃东西"); //base.EatFood(); }
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(); } }
}
运行结果: |
|
来自: ontheroad96j47 > 《待分类》