实现效果:
知识运用:
get和set访问器
[修饰符] [类型 ] [属性名]{
get {get访问器体};
set {set访问器体};
}
实现代码:
private void Form1_Load(object sender, EventArgs e) { student stu = new student(); stu.ID = "S911"; stu.NAME = "莫恐"; label1.Text += "\n\n" + stu.ID + "\n\n" + stu.NAME; stu.ID = "S119"; stu.NAME = "莫慌"; label2.Text += "\n\n" + stu.ID + "\n\n" + stu.NAME; } } class student { private string id = "", name = ""; public string ID { set { id = value; } get { return id; } } public string NAME { set { name = value; } get { return name; } } }
知识补充:
属性名首字母通常大写
在set访问器中不能自定义使用名称为value的局部变量或常量
在set访问器体中允许包含大量语句,因此可以对赋值进行检查,避免进一步的错误