C#封裝以及訪問修飾符
封裝被定義為"把一個或多個專案封閉在一個物理的或者邏輯的包中"。在面向物件程式設計方法論中,封裝是為了防止對實現細節的訪問。
抽象和封裝是面向物件程式設計的相關特性。抽象允許相關資訊視覺化,封裝則使開發者實現所需級別的抽象。
C# 封裝根據具體的需要,設定使用者的訪問許可權,並通過訪問修飾符來實現。
一個訪問修飾符定義了一個類成員的範圍和可見性。C# 支援的訪問修飾符如下所示:
- public:所有物件都可以訪問;
- private:物件本身在物件內部可以訪問;
- protected:只有該類物件及其子類物件可以訪問
- internal:同一個程式集的物件可以訪問;
- protected internal:訪問限於當前程式集或派生自包含類的型別。
-
Public 訪問修飾符
Public 訪問修飾符允許一個類將其成員變數和成員函式暴露給其他的函式和物件。任何公有成員可以被外部的類訪問。
using System; namespace RectangleApplication { class Rectangle { //成員變數 public double length; public double width; public double GetArea() { return length * width; }
View Code在上面的例項中,成員變數 length 和 width 被宣告為public,所以它們可以被函式 Main() 使用 Rectangle 類的例項r訪問。
成員函式Display()和GetArea()可以直接訪問這些變數。
成員函式Display()也被宣告為public,所以它也能被Main()使用 Rectangle 類的例項r訪問。
-
Private 訪問修飾符
Private 訪問修飾符允許一個類將其成員變數和成員函式對其他的函式和物件進行隱藏。只有同一個類中的函式可以訪問它的私有成員。即使是類的例項也不能訪問它的私有成員。
-
using System; namespace RectangleApplication { class Rectangle { //成員變數 private double length; private double width; public void Acceptdetails() { Console.WriteLine("請輸入長度:"); length = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("請輸入寬度:"); width = Convert.ToDouble(Console.ReadLine()); } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("長度: {0}", length); Console.WriteLine("寬度: {0}", width); Console.WriteLine("面積: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.Acceptdetails(); r.Display(); Console.ReadLine(); } } }
View Code在上面的例項中,成員變數 length 和 width 被宣告為private,所以它們不能被函式 Main() 訪問。
成員函式AcceptDetails()和Display()可以訪問這些變數。
由於成員函式AcceptDetails()和Display()被宣告為public,所以它們可以被Main()使用 Rectangle 類的例項r訪問。
-
Protected 訪問修飾符
Protected 訪問修飾符允許子類訪問它的基類的成員變數和成員函式。這樣有助於實現繼承。
-
Internal 訪問修飾符
Internal 訪問說明符允許一個類將其成員變數和成員函式暴露給當前程式中的其他函式和物件。換句話說,帶有 internal 訪問修飾符的任何成員可以被定義在該成員所定義的應用程式內的任何類或方法訪問。
-
using System; namespace RectangleApplication { class Rectangle { //成員變數 internal double length; internal double width; double GetArea() { return length * width; } public void Display() { Console.WriteLine("長度: {0}", length); Console.WriteLine("寬度: {0}", width); Console.WriteLine("面積: {0}", GetArea()); } }//end class Rectangle class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5; r.Display(); Console.ReadLine(); } } }
View Code在上面的例項中,請注意成員函式GetArea()宣告的時候不帶有任何訪問修飾符。如果沒有指定訪問修飾符,則使用類成員的預設訪問修飾符,即為private。
-
Protected Internal 訪問修飾符
Protected Internal 訪問修飾符允許在本類,派生類或者包含該類的程式集中訪問。這也被用於實現繼承。
-
- (1)Pubilc:任何公有成員可以被外部的類訪問。
- (2)Private:只有同一個類中的函式可以訪問它的私有成員。
- (3)Protected:該類內部和繼承類中可以訪問。
- (4)internal: 同一個程式集的物件可以訪問。
- (5)Protected internal:3 和 4 的並集,符合任意一條都可以訪問。
範圍比較:
private < internal/protected < protected internal < public