【问题标题】:Why is there a curly parenthesis in the following C# code? [duplicate]为什么下面的 C# 代码中有一个大括号? [复制]
【发布时间】:2017-07-07 12:46:24
【问题描述】:

我是 C# 新手。我正在关注关于 GUI 框架的视频。我想知道为什么下面代码中的“新标签”后面没有普通括号“()”而是大括号“{}”。

我们不是在这里实例化一个类吗?

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

【问题讨论】:

  • 谷歌的术语是"object initializer"
  • 它是new Label() { Property1 = value1, etc...};调用默认无参数构造函数的单行快捷方式。

标签: c#


【解决方案1】:

这是一个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 在 ctor 中确实有一个参数,如下所示:

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,
};

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2015-09-27
    • 2011-02-07
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2013-06-13
    相关资源
    最近更新 更多