Nested & Access modifiers

Nested types

Class和Structure里可以nest任意多的类型(包括class),但是Enum里不可以。

class
{
    enum ParserState
    {
    }
}
Class Person
{
    Class Room{}
    enum GunType{}
}
View Code

Access modifiers


Internal:只包在本assemble(ClassLibrary编译后是dll,ConsoleApplication16编译后是exe文件,这是两个独立的Assembly)里使用。

其他Assembly不可见。

上面ClassLibrary1是一个class assembly dll,CLass1是internal的所以另外一个assembly应用了这个dll,也不可以new

Private非nest type(即定义class的时候),不可以加private,nest的不一定。只可以显式的public,internal,或者不写默认是iternal

class PersonParser   //默认:internal 
{
    int _privateData;  //默认:private 
    private enum ParserState  //显式:private
    {
    }
}
View Code

Protect: 继承类可以使用protect methord,外面的类不可以使用。使用情况,create base class,创建若干methords,我只想让child class使用这些methord,外面的类不可以使用。

Public VS Private VS Protect总结

  • 左边的图是private,所以不可以被child class或者外部class使用,右边的是protect所以只可以被child class使用,internal是第三位的本assembly都可以用。public全部可见

  • nest后,type.type的写法:

  •  Protected internal:对自己内部是internal,对外部是protect(要使用先继承)。

 

  • Interface里面的filed,methord都是public的

  • 总结:一般尽量上来都给private,若需要多个Assembly共享方法用internal(比如reader,writer方法需要多个project使用),需要外部其他assembly使用再public

Implicit and Explicit Interface Implementations

Implicity:

 

 

Explicity:class Tree 中的Use方法fullfill两个interface,也可以分开用

 

 

        

 

一般写interface的时候,我们可以一个type继承这个interface,ctrl+.就是implicaity创建一个public方法与interface的同名方法关联,如果自己写explicity的话,要写interface.方法,这样这个方法就是private的了。

interface中同一个对象由于使用不同vaiable type所带来不一样的结果

 

 

原文地址:https://www.cnblogs.com/shawnzxx/p/3137372.html