在C#經過好多版本的迭代后,屬性的寫法已經比較豐富了澡绩,最近有用到,順手寫下來:
class Student
{
public Student(string name)
{
Name = name;
}
//定義但不顯式初始化值
public string Name { set; get; }
//值在這里被初始化
private string fatherName = "";
public string FatherName
{
set
{
fatherName = value;
}
get
{
return fatherName;
}
}
//顯式初始化值
public bool Married { set; get; } = false;
//外部只能讀取該屬性而類的內部可以設置
public int UniqueID { private set; get; } = -1;
//只寫屬性
private string nationality;
public string Nationality
{
set
{
nationality= value;
}
}
//只讀屬性的另一種寫法
private string sexual = "Male";
public string Sexual
{
get
{
return sexual;
}
}
//顯式初始化值的只讀屬性俺附,
//要注意這個只讀屬性基本只能用來做常量用肥卡,因為它的值確定以后就沒法變動了
public int Age { get; } = 0;
}
達叔傻樂(darwin.zuo@163.com)