源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

c#中使用自动属性减少代码输入量

  • 时间:2020-03-22 22:06 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:c#中使用自动属性减少代码输入量
[u]复制代码[/u] 代码如下:
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;         }     }
可以改写为:
[u]复制代码[/u] 代码如下:
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);         }     }
代码是不是简化了很多! 注意: 不能定义只读或者只写的属性,必须同时提供 如果想在属性中增加判断、验证等逻辑,则只能用传统的属性定义方法实现  
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部