這是一個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,
};
術語至谷歌是[ 「對象初始化」]( https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers) –
這是一個簡單的快捷方式到'new Label() {Property1 = value1等...};'調用默認的無參數構造函數。 – bradbury9