使用自动属性减少代码输入量
2012-12-03 16:21
218 查看
.Net 3.0中的自动属性可以大幅度降低我们输入的代码量如:
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);
}
}
代码是不是简化了很多!
注意:
不能定义只读或者只写的属性,必须同时提供
如果想在属性中增加判断、验证等逻辑,则只能用传统的属性定义方法实现
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);
}
}
代码是不是简化了很多!
注意:
不能定义只读或者只写的属性,必须同时提供
如果想在属性中增加判断、验证等逻辑,则只能用传统的属性定义方法实现
相关文章推荐
- c#中使用自动属性减少代码输入量
- 使用自动属性减少代码输入量
- C语言宏定义##连接符和#符的使用(MFC就是靠##自动把消息和消息函数对应起来了,借助宏来减少switch case代码的编写量)
- VC6.0下不能自动完成类方法和属性的解决办法(vc6无法使用代码自动完成)
- 使用代码自动创建模型属性
- 使用python代码实现三叉搜索树高效率”自动输入提示”功能
- eclipse 关闭自动加载(重启),使用jreloader更新代码,减少重启次数。
- jquery使用attr访问自定义属性,减少javascript脚本中代码和数据的耦合
- Edittext设置输入属性,包括使用代码设置
- 代码中输入数字自动筛选出最大值,使用array,for loop and if (21.9.2017)
- 使用代码自动创建模型属性
- iOS开发-xcode使用-自动格式化代码
- 如何在Eclipse中使用ibatis的自动代码生成工具Abator
- iOS 8 Auto Layout界面自动布局系列3-使用代码添加布局约束
- android开发使用greenDAO如何自动生成代码
- Eclipse RCP自动输入援助的实现--swtaddons的使用与扩展
- 使用Visual Studio宏来自动生成代码 [ Visual Studio | 宏 | 自动生成代码 ]
- 使用MultiAutoCompleteTextView实现自动匹配输入的内容
- IOS autoLayout之使用VFL语言进行代码自动布局
- 使用codedom自动生成代码