C# 类的派生 输出个人信息

运行结果

C# 类的派生 输出个人信息

代码

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 派生
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Undergraguate u = new Undergraguate();

            string name = textBox2.Text;
            int age = int.Parse(textBox3.Text);
            string subject = textBox4.Text;

            textBox1.Text = u.GetMessage(name, age, subject);//直接将返回值输出到textbox
            textBox1.Text += "\r\n" + u.Study();
        }
    }

    public class Student//基类
    {
        protected string name;
        protected int age;

        public string Study()
        {
            string result;
            result = string.Format("Student({0}):我是基类的方法。我今年{1}岁,我没毕业,正在学习。\r\n", name, age);
            return result;
        }

        public Student()
        {
            this.age = 8;
        }
    }

    public class Undergraguate : Student//派生类 继承于基类 基类中的函数自动吸收进来
    {
        public string subject;//派生类增加的特殊数据成员

        //public Undergraguate()//构造函数 这样就不调用基类的构造函数: base("无名",0)这样调用基类的构造函数
        //{
        //    subject = "未知";
        //}
        public Undergraguate() : base()//继承的构造函数 大括号里面还能赋值 本程序中这段代码对输出结果无作用
        {
            subject = "软工";
            age++;
        }

        public string GetMessage(string name, int age, string subject)
        {
            this.name = name;
            this.age = age;
            this.subject = subject;

            string result;
            result = string.Format("Undergraguate({0}):我是派生类的方法。我今年{1}岁,我毕业了,专业是:{2}\r\n", name, age, subject);
            return result;
        }
    }
}