c#中使用自动属性减少代码输入量
public class product
{
private string name;
public string name
{
get
{
return name;
}
private set
{
name = value;
}
}
private decimal price;
public decimal price
{
get
{
return price;
}
set
{
price = value;
}
}
public product(string name, decimal price)
{
this.price = price;
this.name = name;
}
}
可以改写为:
public class product
{
public string name
{
get;
private set;
}
public decimal price
{
get;
set;
}
public product(string name, decimal price)
{
name = name;
price = price;
}
public override string tostring()
{
return string.format("{0}:{1}", this.name, this.price);
}
}
代码是不是简化了很多!
注意:
不能定义只读或者只写的属性,必须同时提供
如果想在属性中增加判断、验证等逻辑,则只能用传统的属性定义方法实现