在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)
网友评论