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);
}
}
代码是不是简化了很多!
注意:
不能定义只读或者只写的属性,必须同时提供
如果想在属性中增加判断、验证等逻辑,则只能用传统的属性定义方法实现
相关文章
- .Net 3.0中的自动属性可以大幅度降低我们输入的代码量,需要的朋友可以参考下...2020-06-25
- 下面小编就为大家带来一篇减少C++代码编译时间的简单方法(必看篇)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-04-25
- 还记得三层吗?没错 今天就讲我们在写三层的时候使用反射来减少代码的书写量...2021-09-22