编写一个控制台程序,在该程序中构造一个Person基类,再分别构造Student和Teacher派生类,要求具有不同的特征和行为,能通过静态成员自动记录由不同派生类创建的对象的人数。 c#
时间: 2024-12-19 08:27:19 浏览: 3
在C#中,你可以创建一个基础类`Person`,然后创建`Student`和`Teacher`两个派生类,它们各自可以有自己的特性(如姓名、年龄等),并在基类中添加一个静态计数器来跟踪派生类实例的数量。这是一个示例:
```csharp
// Person基类
public abstract class Person
{
protected string name;
protected int age;
public Person(string name, int age)
{
this.name = name;
this.age = age;
StaticCounter++;
}
public virtual void DisplayInfo() // 虚拟方法以便派生类覆盖
{
Console.WriteLine($"{name} is a {typeof(Person).Name}, aged {age}");
}
// 静态计数器
public static int StaticCounter = 0;
// 客户端代码不能直接修改这个静态属性,只能增加或减少
public static int Count => StaticCounter;
protected static void IncCounter() => StaticCounter++;
}
// Student派生类
public class Student : Person
{
public string major;
public Student(string name, int age, string major) : base(name, age)
{
this.major = major;
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"They are studying {major}");
}
}
// Teacher派生类
public class Teacher : Person
{
public string subject;
public Teacher(string name, int age, string subject) : base(name, age)
{
this.subject = subject;
}
public override void DisplayInfo()
{
base.DisplayInfo();
Console.WriteLine($"They teach {subject}");
}
}
class Program
{
static void Main(string[] args)
{
// 创建并显示对象信息
var student1 = new Student("Alice", 20, "Computer Science");
var teacher1 = new Teacher("Bob", 40, "Mathematics");
student1.DisplayInfo();
teacher1.DisplayInfo();
Console.WriteLine($"Total instances created: {Person.Count}");
}
}
```
当你运行这个程序,每次创建`Student`或`Teacher`实例时,都会自动增加`StaticCounter`的值。
阅读全文