c#中set访问器始终使用什么东西来设置属性的值
在C#中,set访问器可以使用任何合法的语句来设置属性的值,例如:
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
在这个例子中,set访问器使用了一个简单的赋值语句将传入的值赋给了私有字段_age。但是,set访问器也可以使用其他逻辑来计算属性的值,例如:
public int Age
{
get { return _age; }
set
{
if (value < 0)
throw new ArgumentException("Age cannot be negative.");
_age = value;
}
}
在这个例子中,set访问器检查传入的值是否小于0,如果是则抛出ArgumentException异常,否则将传入的值赋给_age字段。
原文地址: http://www.cveoy.top/t/topic/fq1u 著作权归作者所有。请勿转载和采集!