用c#写出一个学生类和一个子类学生类要有名字和年龄两个属性和两个包含参数的方法用于给名字和年龄赋值一个show方法打印学生类的信息子类加一个学位属性。一个包含3个参数的构造方法用于继承名字和年龄的属性赋值第三个参数用于给学位属性赋值用show方法打印出子类的属性信息在测试类中分别创建学生类和子类对象调用他们的show方法
学生类代码:
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public void SetName(string name)
{
this.Name = name;
}
public void SetAge(int age)
{
this.Age = age;
}
public void Show()
{
Console.WriteLine("Name: {0}", this.Name);
Console.WriteLine("Age: {0}", this.Age);
}
}
子类代码:
class GraduateStudent : Student
{
public string Degree { get; set; }
public GraduateStudent(string name, int age, string degree)
{
this.Name = name;
this.Age = age;
this.Degree = degree;
}
public void Show()
{
base.Show();
Console.WriteLine("Degree: {0}", this.Degree);
}
}
测试类代码:
class Program
{
static void Main(string[] args)
{
// 创建学生对象
Student s = new Student();
s.SetName("张三");
s.SetAge(18);
s.Show();
// 创建研究生对象
GraduateStudent gs = new GraduateStudent("李四", 25, "硕士");
gs.Show();
Console.ReadKey();
}
}
``
原文地址: https://www.cveoy.top/t/topic/ckTZ 著作权归作者所有。请勿转载和采集!