1、当引用属性时,除非该属性为赋值目标,否则将调用get访问器读取该属性的值。
例如:Employeee1=newEmployee();...Console.Write(e1.Name);//Thegetaccessorisinvokedhereget
访问器必须在return或throw语句中终止,并且控制不能超出访问器体。
2、set访问器与返回void的方法类似,它使用称为value的隐式参数,此参数的类型是属性的类型。
set访问器被添加到Name属性:
publicstringName
{
get{returnname;}
set{name=value;}
}
当对属性赋值时,用提供新值的参数调用set访问器。
例如:e1.Name="Joe";//Thesetaccessorisinvokedhere在set访问器中对局部变量声明使用隐式参数名(value)是错误的。
扩展资料
get的使用
publicclassCar
{
publicstringColor
{
get{
if(this.viewstate["color"]!=null)
{
returnthis.viewstate["color"];
}
return"":
}
set{this.viewstate["color"];=value;}
}
}
首先,get和set是属性特有的两个方法。属性是对字段的封装,是为了程序数据的安全性考虑的。总的来说,字段有两种操作权限,就是获取和修改,就分别对应的是get和set方法了,可以通过制定get和set方法来限定字段的访问权限。
例如:
private int _age;//年龄 字段