类属性
初学C#,对许多概念不甚了解,就比如这个属性,做个笔记
C#中“属性”概念是类字段的访问器(getter/setter)
using System;
namespace Hello
{
class Shape
{
// 两个私有成员变量(字段)
private int _width;
private int _height;
// 定义了width属性,其包含了对_width字段的getter和setter
public int width
{
// 这里的value是默认隐含的参数
set { this._width = value; }
get { return this._width; }
}
public int height
{
set { this._height = value; }
get { return this._height; }
}
public int square()
{
return this._width * this._height;
}
}
public class Program
{
public static void Main()
{
Shape shape = new Shape();
// 此处赋值操作的10就是width属性中setter的隐含参数value
shape.width = 10;
shape.height = 20;
Console.WriteLine("{0}", shape.square());
shape.width = 30;
shape.height = 40;
Console.WriteLine("{0}", shape.square());
}
}
}