1.C#中只支持单继承而不支持多重继承。即在C#里面一次只允许继承一个类,不能同时继承多个类。如下图:
2.子类的可访问性一定要低于或等于父类的可访问性。父类的访问性默认为private,子类的public访问性就高于了父类而出现错误。
3.子类重写父类中的方法时候,还要调用父类中原方法的时候,可以使用关键字Base.Base关键字代表父类对象。子类中重写父类中的方法时候,要在方法类型前面加上new关键字来隐藏父类中的方法。否则会出现下图中的错误提示:
因为父类中的方法,参数,返回值类型都一样会引起歧义。加入new就可以隐藏父类的sayhello方法了。
using System;
namespace 继承
{
class computer
{
public string sayhello()
{
return "欢迎使用";
}
}
class notebook : computer
{
public new string sayhello()
{
return base.sayhello() + "笔记本电脑";
}
}
class Program
{
static void Main(string[] args)
{
computer pc = new computer();
Console.WriteLine(pc.sayhello());
notebook nb = new notebook();
Console.WriteLine(nb.sayhello());
Console.ReadKey();
}
}
}