实现效果:
知识运用:
实现代码:
class People { //定义一个虚方法表示人说话的行为 public virtual void Say(RichTextBox rtb, string name){ rtb.Text += name; } } class Chinese : People { //定义派生类继承于People类 public override void Say(RichTextBox rtb, string name) //重写基类中的虚方法 { base.Say(rtb,name+"说汉语 "); } } class American : People { public override void Say(RichTextBox rtb, string name) { base.Say(rtb, name+"说英语"); } } private void button1_Click(object sender, EventArgs e) { if (textBox1.Text == string.Empty) //判断输入为空 { MessageBox.Show("请输入姓名"); return; } richTextBox1.Clear(); //清空内容 People[] people = new People[2]; //创建People类数组 people[0] = new Chinese(); //添加值 people[1] = new American(); foreach(People p in people){ //遍历输出 p.Say(richTextBox1,textBox1.Text); } }
补充说明: