把一個,或者多個項目,封閉在一個物理,或者邏輯的包中。
C# 封裝,可設置訪問權限,通過 訪問修飾符 來實現。
訪問修飾符,定義一個類成員的範圍和可見性。
C# 支持的訪問修飾符:
- public:所有對象都可以訪問。
- private:對象本身在內部進行訪問。
- protected:該類,及其子類可以訪問。
- internal:同一程序集的對象可以訪問。
- protected internal:當前程序集,或派生自包含類的類型。
一、public
一個類的成員變量和成員函數,可被外部的類訪問。
using System;
namespace RectangleApplication
{
class Rectangle
{
//成員變量
public double length;
public double width;
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("長度: {0}", length);
Console.WriteLine("寬度: {0}", width);
Console.WriteLine("面積: {0}", GetArea());
}
}// Rectangle 結束
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
// 實例化類
r.length = 4.5; // 訪問該類下的屬性
r.width = 3.5;
r.Display(); // 訪問該類下的方法
Console.ReadLine();
}
}
}
運行結果:
長度: 4.5
寬度: 3.5
面積: 15.75
二、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();
}
}
}
運行結果:
請輸入長度:
2
請輸入寬度:
3
長度: 2
寬度: 3
面積: 6
總結:
這裏 Rectangle 類中,length 和 width 兩個變量爲 private。
所以無法通過外部的類進行訪問。
需要首先通過外部的類訪問 Acceptdetails() 這個方法,這個方法是 public,所以外部類可以訪問,然後通過這個方法來設置 length 和 width。
三、protected
允許子類訪問,有助於實現繼承。
四、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();
}
}
}
運行結果:
長度: 4.5
寬度: 3.5
面積: 15.75
由於 Rectangle 和 ExecuteRectangle 兩個類位於同一程序中,所以 ExecuteRectangle 可以訪問 length 和 width。
GetArea() 方法由於不帶修飾符,所以默認爲 private,只能通過 Display() 來進行訪問。
六、protected internal
允許在本類,派生類或者包含該類的程序集中訪問。
同樣用於實現繼承。