嵌套类存在的理由:
一个类在它包容类外部没有多大意义的时候,设计成嵌套类更为妥当一些。
嵌套类的特点:
1.由于它只与包容类产生关系,所以应该需要防止从包容类外部访问它。那么当类是嵌套类的时候,要使用private访
问修饰符来修饰嵌套类,这样就可以限定嵌套类的作用域了。
2.嵌套类能访问包容类的所有成员,包括私有成员。
3.包容类不能访问嵌套类的私有成员。
4.一般情况下,尽量避免使用public修饰嵌套类。
继承
1.派生类型可以直接赋给基类型(隐式转换);基类型却不能直接赋给派生类型。
2.需要将基类型转换成派生类型,需要显式转换。
3.继承链是没有限制的。
4.每个派生类拥有基类所有公开的所有成员。
5.对4进行补充,所有成员包含私有成员。换言之,私有成员被继承但不能被访问。
看下面例子:
public sealed partial class InheritanceExample : Page
{
public string GuidKey { get; set; }
private string Address;
public InheritanceExample()
{
this.InitializeComponent();
MeiZu meizu = new MeiZu();
meizu.ScreenSize = 5;
//包容类不能访问嵌套类的私有成员
//meizu._OperationSystem = "Flyme"; -- 错误
XiaoMi xiaomi1 = new XiaoMi();
//隐式转换。因为派生类型XiaoMi属于Phone类型,所以可以直接赋给Phone类型的变量
Phone phone1 = xiaomi1;
Phone phone2 = new Phone();
//显式转换。因为Phone类型不一定是XiaoMi,也可能是MeiZu,所以需要添加转型操作符
XiaoMi xiaomi2 = (XiaoMi)phone2;
XiaoMi xiaomi3 = new XiaoMi();
//Phone类中的私有成员虽然被继承了,但是在继承类中不能被访问
//xiaomi3._Price = 999; -- 错误
}
private class MeiZu:Phone
{
public int ScreenSize { get; set; }
private string _OperationSystem;
public void GetNameAddress(string guidKey,string address)
{
InheritanceExample inheritance = new InheritanceExample();
inheritance.GuidKey = guidKey;
//嵌套类能访问包容类的私有成员
inheritance.Address = address;
}
}
}
class Phone
{
public string Brand { get; set; }
private int _Price;
}
class XiaoMi:Phone
{
public int ScreenSize { get; set; }
public string OperationSystem { get; set; }
}