c# 多态 代码示例
时间: 2023-12-08 10:39:15 浏览: 85
以下是一个C#多态的代码示例:
```csharp
// 定义一个Person类
public class Person
{
protected string name;
public Person(string name)
{
this.name = name;
}
public virtual void SayHello()
{
Console.WriteLine("Hello, I am {0}.", name);
}
}
// 定一个Student类,继承自Person类
public class Student : Person
{
public Student(string name) : base(name)
{
}
public override void SayHello()
{
Console.WriteLine("Hello, I am a student, my name is {0}.", name);
}
}
// 定义一个Teacher类,继承自Person类
public class Teacher : Person
{
public Teacher(string name) : base(name)
{
}
public override void SayHello()
{
Console.WriteLine("Hello, I am a teacher, my name is {0}.", name);
}
}
// 在Main函数中使用多态
Person[] p = { new Student("李雷"), new Teacher("井边君") };
for (int i = 0; i < p.Length; i++)
{
p[i].SayHello();
}
```
输出结果为:
```
Hello, I am a student, my name is 李雷.
Hello, I am a teacher, my name is 井边君.
```
阅读全文