类是在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