继承相关的关键字:Virtual,new,base,abstract,sealed....
1.C#中的继承分为实现继承,接口继承。
c#类可以派生于另一个类和任意多个接口。
2.关键字
Virtual: 虚方法
虚方法与面向对象的多态性有很大的关系。
在基类中定义虚方法用virtual,方法有实现部分。
派生类可以重写该虚方法,也可以不重写。重写用关键字override.
重写override也叫覆盖:
-
不同的范围(基类和派生类)
-
函数名和参数相同
-
重写的函数必须是基类的虚函数。
New:显示隐藏
如果基类中的函数没有用virtual修饰,派生类想重写基类的方法,那么不用Override,叫隐藏。用关键字new显示隐藏。
hide
Base:在派生类中调用基类被隐藏的函数
举例:
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.setHA(158, 20);
Console.WriteLine(stu.getHeight());
Console.WriteLine(stu.getAge());
Console.WriteLine(stu.getAge(20));
People pe = new Student();
pe.setHA(170, 25);
Console.WriteLine("height={0},age={1}", pe.getHeight(),
pe.getAge());
}
}
class
People
{
public int height;
public int age;
public void setHA(int h, int a)
{
height = h;
age = a;
}
public virtual int getHeight()
{
return height;
}
public int getAge()
{
return age;
}
}
class
Student : People
{
public override int getHeight() //重写
{
return height + 5;
}
public new int getAge() //隐藏
{
return age + 5;