什麼是 C# 中的封裝?
C# 中的封裝阻止對實現細節的訪問。使用訪問限定符在 C# 中實現封裝。
C# 支援以下訪問限定符 -
- 公共
- 私有
- 受保護
- 內部
- 受保護的內部
可以透過允許類對其他函式和物件隱藏其成員變數和成員函式的私有訪問限定符示例來理解封裝。
在以下示例中,我們具有分配了私有訪問限定符的變數長度和寬度 -
示例
using System;
namespace RectangleApplication {
class Rectangle {
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 15;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}輸出
Length: 10 Width: 15 Area: 150
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP