定义一个人员类CPerson,包括字段:姓名,编号、性别,以及用于输入/输出的方法。在此基础上派生出学生类CStudent(增加“成绩”字段)和教师类(增加“教龄:字段),并实现对学生和教师信息的输入/输出。使用C#语言实现
时间: 2024-10-27 16:05:24 浏览: 25
C# 类的声明格式
首先,我们可以定义一个名为`CPerson`的基础人员类,包含姓名、编号和性别的属性:
```csharp
public class CPerson
{
public string Name { get; set; }
public int ID { get; set; }
public string Gender { get; set; }
// 构造函数
public CPerson(string name, int id, string gender)
{
Name = name;
ID = id;
Gender = gender;
}
// 输入/输出方法
public override string ToString()
{
return $"姓名:{Name}, 编号:{ID}, 性别:{Gender}";
}
}
```
接着,我们为学生类`CStudent`添加成绩属性,并覆盖`ToString()`方法:
```csharp
public class CStudent : CPerson
{
public float Score { get; set; }
public CStudent(string name, int id, string gender, float score) : base(name, id, gender)
{
Score = score;
}
public override string ToString()
{
return $"{base.ToString()}, 成绩:{Score}";
}
}
```
最后,为教师类`CTeacher`添加教龄属性:
```csharp
public class CTeacher : CPerson
{
public int TeachingYears { get; set; }
public CTeacher(string name, int id, string gender, int teachingYears) : base(name, id, gender)
{
TeachingYears = teachingYears;
}
public override string ToString()
{
return $"{base.ToString()}, 教龄:{TeachingYears}年";
}
}
```
现在可以对这三类的对象进行输入/输出操作:
```csharp
// 创建实例并输出
CStudent student = new CStudent("张三", 1001, "男", 85.5f);
Console.WriteLine(student);
CTeacher teacher = new CTeacher("李四", 2002, "女", 10);
Console.WriteLine(teacher);
```
阅读全文