C#中的internal關鍵字

 internal關鍵字是類型和類型成員的訪問修飾符。只有在同一個程序集的文件中,內部類型或者是成員才能夠訪問。這是msdn上對internal的描述。只有這麼一句話,可是具體怎麼理解呢?類型就是enum(枚舉類型),class(類),interface(接口),struct(結構)等類型。類型成員如函數,成員變量等。那麼什麼是程序集呢?根據msdn上通俗易懂的解釋就是,一個完整的.exe或者是.dll文件就是一個程序集,通常伴隨着exe程序集產生的還有一個程序集清單,.exe.config文件。下面我就用一個例子來講明「internal關鍵字是類型和類型成員的訪問修飾符。只有在同一個程序集的文件中,內部類型或者是成員才能夠訪問」。html

 首先建立一個visual C#的class libiary項目,在該項目中建立Class1,Class2,Class3,Class 4,Class5以下ide

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";
   }this

class Class4 : Class3
   {
       public string GetInternal()
       {
           return this.str3;
       }
       public string GetProtected()
       {
           return this.str1;
       }
       public string Getpublic()
       {
           return this.str2;
       }
   }url

 

 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;
       }
   }3d

如今已經有用internal修飾的類型和類型成員了。                        orm

1.從Class1,Class2和Class5中咱們能夠看到在同一個程序集中(由於Class1,Class2和Class5都是在同一個dll文件中的),internal修飾的類型成員就和public修飾的同樣能夠被子類調用也能夠被被其餘的類型調用,而protected internal則和protected等價,不能被非子類調用。htm

C#中的internal關鍵字學習

                        圖1 在繼承類中internal修飾類型成員

C#中的internal關鍵字學習blog

                圖2 在其餘類中的internal修飾類型成員

2.從Class3,Class4和Class5中,咱們能夠看到internal修飾的類型就和public修飾的同樣,protected internal則和protected等價。

C#中的internal關鍵字學習

                      圖3 internal修飾的繼承類

C#中的internal關鍵字學習

             圖4在其餘類中調用internal修飾的類

   在不一樣程序集中調用internal修飾的類型和類型成員。新建一個winform項目,在該項目中添加對上面建立的dll文件---TestInternallib.dLL。

1.internal修飾的類型

C#中的internal關鍵字學習

    圖5 internal修飾的class不可見,只有Class1和Class2

2.intrnal修飾的類型成員的引用

C#中的internal關鍵字學習

                 圖7 internal修飾的類型成員都不可見

 OK,到此爲止,解釋清楚了internal的描述。

相關文章
相關標籤/搜索