在 C# 中,類的公共成員變數的範圍是什麼?
公共訪問說明符允許類向其他函式和物件公開其成員變數和成員函式。可從類外訪問任何公共成員。
在下面示例中,length 和 width 變數已被宣告為公共。現在你甚至可以在 Main() 方法外訪問它們。
使用類的例項訪問這些變數。
Rectangle r = new Rectangle(); r.length = 4.5; r.width = 3.5;
我們來看看完整程式碼。
示例
Using System;
namespace RectangleApplication {
class Rectangle {
// member variables
public double length;
public double width;
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.length = 4.5;
r.width = 3.5;
r.Display();
Console.ReadLine();
}
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP