2017-07-07 22 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, 
}; 
相关问题