c#get和set用法详解

如题所述

第1个回答  2022-11-16

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;}

}

}

相似回答