2017-07-07 25 views
0

我是C#中的新成員。我正在一個GUI框架中觀看視頻。我想知道爲什麼沒有正常的括號'()',而是在下面的代碼中的'新標籤'之後的括號括號'{}'。爲什麼在下面的C#代碼中有一個花括號?

我們是不是在這裏實例化一個類?

Content = new Label { 
    HorizontalOptions = LayoutOptions.Center, 
    VerticalOptions = LayoutOptions.Center, 
    Text = "Hello word" 
}; 
+6

術語至谷歌是[ 「對象初始化」]( https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers) –

+0

這是一個簡單的快捷方式到'new Label() {Property1 = value1等...};'調用默認的無參數構造函數。 – bradbury9

回答

2

這是一個object initializer - 在推出C#3.0

Content = new Label { 
    HorizontalOptions = LayoutOptions.Center, 
    VerticalOptions = LayoutOptions.Center, 
    Text = "Hello word" 
}; 

如果Label有一個參數的構造函數纔有效。
我們可以假設Label看起來是這樣的:

public class Label 
{ 
    public Label() 
    { 
     //this empty ctor is not required by the compiler 
     //just here for illustration 
    } 

    public string HorizontalOptions {get;set} 
    public string VerticalOptions {get;set} 
    public string Text {get;set} 
} 

對象初始化器設置屬性,當它實例化。

然而,如果Label並具有在構造函數的參數,例如:

public class Label 
{ 
    public Label(string text) 
    { 
     Text = text 
    } 

    public string HorizontalOptions {get;set} 
    public string VerticalOptions {get;set} 
    public string Text {get;set} 
} 

那麼這將是等效

Content = new Label("Hello World") { //notice I'm passing parameter to ctor here 
    HorizontalOptions = LayoutOptions.Center, 
    VerticalOptions = LayoutOptions.Center, 
}; 
相關問題