C#中的类的成员变量是什么?
类是在C#中具有成员变量和函数的蓝图。这描述了对象的行为。
让我们看一看类的语法以了解什么是成员变量-
<access specifier> class class_name {
//成员变量
<access specifier> <data type> variable1;
<access specifier> <data type> variable2;
...
<access specifier> <data type> variableN;
//成员方法
<access specifier> <return type> method1(parameter_list) {
//方法主体
}
<access specifier> <return type> method2(parameter_list) {
//方法主体
}
...
<access specifier> <return type> methodN(parameter_list) {
//方法主体
}
}成员变量是对象的属性(从设计的角度来看),并且对它们进行私有化以实现封装。这些变量只能使用公共成员函数访问。
在长度和宽度下方是成员变量,因为将为Rectangle类的每个新实例创建该变量的新实例。
示例
using System;
namespace RectangleApplication {
class Rectangle {
//成员变量
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
热门推荐
10 祖国生日祝福语简短英文
11 佛教生日祝福语简短大全
12 带清的简短祝福语
13 生日祝福语简短独特的
14 月子小孩祝福语大全简短
15 生日牌祝福语英语简短
16 宝宝生日祝福语大全简短
17 2026年春节祝福语简短
18 姐姐女儿结婚祝福语简短