c#中的多态

多态:不同的对象收到相同的消息时,会产生不同的行为
多态的两种体现形式
1.重写父类方法
1>使用new关键字,隐藏父类方法
public class Person
{
public void Show()
{
Console.WriteLine("我是人别害怕");
}
}
public class Teacher:Person
{
public new void Show()
{
Console.WriteLine("我是老师别害怕");
}
}
class Program
{
static void Main(string[] args)
{
Teacher t = new Teacher();
t.Show();
}
}
2>虚方法重写
将父类中的方法用virtual修饰,子类中用override关键字重写父类方法
public class Person
{
public virtual void Show()
{
Console.WriteLine("我是人别害怕");
}
}
public class Teacher:Person
{
public override void Show()
{
Console.WriteLine("我是老师别害怕");
}
}
注意:
   ①虚方法不能用 static 修饰
   ②虚方法不能用 private 修饰,因为虚方法就是让子类来重写的,如果声明为 private,子类就无法重写,所以不能是私有的
   ③虚方法中要有方法体,可以被子类重写,也可以不被子类重写
3>抽象方法重写
public class Person
{
public abstract void Show();
}
public class Teacher:Person
{
public override void Show()
{
Console.WriteLine("我是老师别害怕");
}
}
4>使用new关键字和使用override的区别
new:子类中还有父类的方法,只不过父类的方法被隐藏了
override:子类的方法覆盖了父类的方法
例子:
//使用new关键字
public class Person
{
public void Show()
{
Console.WriteLine("我是人别害怕");
}
}
public class Teacher:Person
{
public new void Show()
{
Console.WriteLine("我是老师别害怕");
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Teacher();
p.show(); //调用父类的方法
Teacher t = new Teacher();
t.Show(); //调用子类自己的方法
((Person)t).show(); //仍然调用父类的方法

}
}
//使用override重写父类的方法
public class Person
{
public virtual void Show()
{
Console.WriteLine("我是人别害怕");
}
}
public class Teacher:Person
{
public override void Show()
{
Console.WriteLine("我是老师别害怕");
}
}
public class Student:Person
{
public override void Show()
{
Console.WriteLine("我是学生别害怕");
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.show(); //调用Person类的方法
Person t = new Teacher();
p.show(); //调用Teacher类的方法
Person s = new Student();
s.show(); //调用Student类的方法
}
}
2.接口
接口也是多态的一种体现,接口是一种规范,它规定了能干什么,如果某一个类实现了接口,就必须实现接口中的方法。
interface IFly
{
void IFly();
}
public class Teacher:Person,IFly
{
public void IFly()
{
Console.WriteLine("我是老师,我会飞");
}
}
public class Student:IFly
{
public void IFly()
{
Console.WriteLine("我是学生,我会飞");
}
}
class Program
{
static void Main(string[] args)
{
IFly ifly = new Teacher();
ifly.IFly();
IFly ifly = new Student();
ifly.IFly();
}
}

猜你喜欢

转载自www.cnblogs.com/alan-1996/p/9812810.html