類屬性
初學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());
}
}
}