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);
}
}
代碼是不是簡化了很多!
注意:
不能定義只讀或者只寫的屬性,必須同時提供
如果想在屬性中增加判斷、驗證等邏輯,則只能用傳統(tǒng)的屬性定義方法實現(xiàn)
相關文章
基于WebRequest.RegisterPrefix的使用詳解
本篇文章對WebRequest.RegisterPrefix的使用進行了詳細的分析介紹,需要的朋友參考下2013-05-05C#中數組、ArrayList、List、Dictionary的用法與區(qū)別淺析(存取數據)
在工作中經常遇到C#數組、ArrayList、List、Dictionary存取數據,但是該選擇哪種類型進行存儲數據呢?很迷茫,今天小編抽空給大家整理下這方面的內容,需要的朋友參考下吧2017-02-02Unity 按鈕事件封裝操作(EventTriggerListener)
這篇文章主要介紹了Unity 按鈕事件封裝操作(EventTriggerListener),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04深入淺析c#靜態(tài)多態(tài)性與動態(tài)多態(tài)性
多態(tài)就是多種形態(tài),也就是對不同對象發(fā)送同一個消息,不同對象會做出不同的響應。這篇文章主要介紹了c#靜態(tài)多態(tài)性與動態(tài)多態(tài)性的相關知識,需要的朋友可以參考下2018-09-09