在 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