C# 中類的私有成員變數的範圍是什麼?
只有同一個類的函式可以訪問它的私有成員。私有訪問說明符允許類隱藏它的成員變數和成員函式,讓其他函式和物件訪問不到。
示例
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 14;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
} //end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}輸出
Length: 10 Width: 14 Area: 140
上面,變數 length 和 width 宣告為私有;因此同一類的函式可以訪問它。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP