我是编程的“空降部队”,一开始就深入项目,研究项目,项目有需要就去学习,所以对于很多基础知识都不是很扎实。但是基础知识是编程的桥梁,没有桥梁就别想盖高楼大厦。所以,我在今后的学习工作中会不断补充基础知识。我写这篇文章来记录我自己的理解,方便以后用到的时候可以查阅。o(∩_∩)o ,我应该多写点文章来总结下我自己的学习心得,体会等,这样能提高得快点。
网上关于internal关键字的说明有很多,但是用我自己理解的方式来记录,会更容易记忆和理解。
internal关键字是类型和类型成员的访问修饰符。只有在同一个程序集的文件中,内部类型或者是成员才可以访问。这是msdn上对internal的描述。只有这么一句话,但是具体怎么理解呢?类型就是enum(枚举类型),class(类),interface(接口),struct(结构)等类型。类型成员如函数,成员变量等。那么什么是程序集呢?根据msdn上通俗易懂的解释就是,一个完整的.exe或者是.dll文件就是一个程序集,一般伴随着exe程序集产生的还有一个程序集清单,.exe.config文件。下面我就用一个例子来说明“internal关键字是类型和类型成员的访问修饰符。只有在同一个程序集的文件中,内部类型或者是成员才可以访问”。
首先创建一个visual C#的class libiary项目,在该项目中创建Class1,Class2,Class3,Class 4,Class5如下
public class Class1
{ protected internal string OtherDll="This is Other dll protected internal"; protected string Otherstr = "This is other dll protected"; internal string OtherDll1 = "This is Other dll internal"; }public class Class2 : Class1
{ public string GetInternal() { return this.OtherDll; } public string GetProtectedInternal() { return this.OtherDll1; } public string GetProtected() { return this.Otherstr; } }internal class Class3
{ protected string str1 = "this is a test internal class protected attribute"; public string str2 = "This is a test internal class public sttribute"; internal string str3 = "This is a test internal class internal attribute"; }class Class4 : Class3
{ public string GetInternal() { return this.str3; } public string GetProtected() { return this.str1; } public string Getpublic() { return this.str2; } }
public class Class5
{ Class1 cla1 = new Class1(); Class3 cls3 = new Class3(); public string GetInternal() { return cla1.OtherDll; } public string GetProtectedInternal() { return cla1.OtherDll1; } public string Getpublic() { return cls3.str2; } public string GetInternal1() { return cls3.str3; } }现在已经有用internal修饰的类型和类型成员了。
1.从Class1,Class2和Class5中我们可以看到在同一个程序集中(因为Class1,Class2和Class5都是在同一个dll文件中的),internal修饰的类型成员就和public修饰的一样可以被子类调用也可以被被其他的类型调用,而protected internal则和protected等价,不能被非子类调用。
图1 在继承类中internal修饰类型成员
图2 在其他类中的internal修饰类型成员
2.从Class3,Class4和Class5中,我们可以看到internal修饰的类型就和public修饰的一样,protected internal则和protected等价。
图3 internal修饰的继承类
图4在其他类中调用internal修饰的类在不同程序集中调用internal修饰的类型和类型成员。新建一个winform项目,在该项目中添加对上面创建的dll文件---TestInternallib.dLL。
1.internal修饰的类型
图5 internal修饰的class不可见,只有Class1和Class22.intrnal修饰的类型成员的引用
图7 internal修饰的类型成员都不可见OK,到此为止,解释清楚了internal的描述。问题虽小,但是积少成多,以后就是宝贵的财富。