差6

2015-10-20 41 views
6

是什麼在C#6初始化屬性下面的表達式之間的區別:差6

1.自動財產構造

public class Context1 
{ 
    public Context1() 
    { 
     this.Items = new List<string>(); 
    } 

    public List<string> Items { get; private set; } 
} 
初始化

2:屬性從背場

public class Context2 
{ 
    private readonly List<string> items; 

    public Context2() 
    { 
     this.items = new List<string>(); 
    } 

    public List<string> Items 
    { 
     get 
     { 
      return this.items; 
     } 
    } 
} 
初始化

3:在C#自動屬性的新語法6

public class Context3 
{ 
    public List<string> Items { get; } = new List<string>(); 
} 

4:在C#自動屬性的新語法6

public class Context4 
{ 
    public List<string> Items => new List<string>(); 
} 

回答

13

清單3是C#6的等價清單2中,其中背部領域提供在引擎蓋下。

清單4:

public List<string> Items => new List<string>(); 

等同於:

public List<string> Items { get { return new List<string>(); } } 

正如你可以想像每次訪問屬性時返回一個新的空單。

清單2/3和4之間的區別在this Q&A中有一個例子。

清單1只是一個帶有getter和private setter的自動屬性。它不是隻讀屬性,您可以在任何可以訪問任何類型的私有成員的位置設置它。只讀屬性(即只有getter屬性)可以在構造函數或屬性聲明中初始化,只是,非常像readonly字段。

+0

所以編號4是像一個常數,而是隨着引用類型!? –

+7

如果用「常量」表示「不斷返回此值的新實例」(àla https://xkcd.com/221),那麼......呃,我想是這樣的。但這不是「常量」的意思。有一個原因引用類型*不能*是常量。 – BoltClock

+0

數字1和2是否相似? –

3

自動財產自動實現的屬性,這裏的開發商並不需要顯式聲明支持字段短名稱和編譯器將設置一個在背後。

1.自動屬性與私人二傳手

public class Context1 
{ 
    public Context1() 
    { 
     this.Items = new List<string>(); 
    } 

    public List<string> Items { get; private set; } 
} 

自動屬性可以通過指定爲它的輔助功能從屬性的輔助功能不同的訪問更嚴格的可訪問性有setter和getter不同的可接近性。

其他例子是:

public string Prop1 { get; private set; } 
public string Prop2 { get; protected set; } 
public string Prop3 { get; internal set; } 
public string Prop4 { protected internal get; set; } 

這些訪問不同的輔助功能可以訪問任何地方是無障礙決定,而不是僅僅從構造函數。

2。帶後盾的只讀屬性

公共類Context2 私有隻讀列表項目;

public Context2() 
{ 
    this.items = new List<string>(); 
} 

public List<string> Items 
{ 
    get { return this.items; } 
} 

} 之前C#6,設置只讀屬性的值的唯一方法是顯式聲明支持字段和直接設置它。

由於該字段具有readonly訪問器,因此只能在構建對象時設置該訪問器。

3.只讀自動物業

public class Context3 
{ 
    public List<string> Items { get; } = new List<string>(); 
} 

初始的C#6,§2可以由編譯器處理的有一個後備字段產生像讀寫自動屬性,但,在這種情況下,後臺字段是隻讀的,只能在構建對象時設置。

4只讀自動屬性與表達濃郁的getter

public class Context4 
{ 
    public List<string> Items => new List<string>(); 
} 

當屬性有變化,每它得到的時間值,C#6允許使用申報吸氣的體一個lambda樣語法。

上面的代碼等效於此:

public class Context4 
{ 
    public List<string> Items 
    { 
     get { return new List<string>(); } 
    } 
}