这是一个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