C# 继承类实例讲解

//创建基类

     class Student

     {

         protected string Id,Name,Sex;

         public Student(string id,string name,string sex)

         {

              Id=id;

              Name=name;

              Sex=sex;

         }

         public string Show()

         {

              return "学号:"+this.Id+",姓名:"+Name+",性别:"+Sex;

         }

     }

     //创建派生类

     class Stu:Student

     {

         private byte Score1,Score2;

         public Stu(string id,string name,string sex,byte score1,byte score2):base(id,name,sex)

         {

              this.Score1=score1;

              this.Score2=score2;

         }

         public uint Total()

         {

              return (uint)Score1+(uint)Score2;

         }

         public float Avarage()

         {

              return (float)(Score1+Score2)/2;

         }

     }

         private void button1_Click(object sender, System.EventArgs e)

         {

              if(txtId.Text=="")

                   return;

              label1.Text="";

              byte Math=byte.Parse(txtMath.Text);

              byte Phy=byte.Parse(txtPhy.Text);

              Stu s1=new Stu(txtId.Text,txtName.Text,txtSex.Text,Math,Phy);

              label1.Text=s1.Show()+"/n平均分:"+s1.Avarage()+",总分:"+s1.Total();

         }

 

         private void Form1_Load(object sender, System.EventArgs e)

         {

              /*声明并实例化类对象*/

              Stu s=new Stu("0604382","王庆坤","",96,99);

              label1.Text=s.Show()+"/n平均分:"+s.Avarage()+",总分:"+s.Total();

         }

很简单吧!一看就能明白其中的道理

你可能感兴趣的:(程序杂谈)