【问题标题】:'Cannot initialize type with a collection initializer' while initializing object of my class初始化我的类的对象时,“无法使用集合初始化程序初始化类型”
【发布时间】:2016-08-26 09:35:37
【问题描述】:

我有一个很奇怪的问题。

这是我定义的一个类:

public class HeaderTagControlsPair
{
    public TextBlock HeaderTextBlock = new TextBlock();
    public ComboBox TagComboBox = new ComboBox();
    public RowDefinition Row = new RowDefinition();
}

现在,我要创建这个类的一个对象并初始化它:

    HeaderTagControlsPair example = new HeaderTagControlsPair
    {
        HeaderTextBlock.Text = "test"
    };

我做不到。我得到了这三个错误:

Error   1   Cannot initialize type 'CSV_To_Tags_App.HeaderTagControlsPair' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
Error   2   Invalid initializer member declarator   
Error   3   The name 'HeaderTextBlock' does not exist in the current context

我不知道为什么会这样,我只是在使用简单的对象初始化。我做错了什么?

【问题讨论】:

  • 至少发生其中一个错误是因为您在未初始化的情况下访问了HeaderTextBlockText 属性。考虑尝试HeaderTagControlsPair example = new HeaderTagControlsPair();,然后设置单独的值,或者使用“test”字符串(例如tb)声明一个新的TextBlock元素并在声明中设置HeaderTextBlock.Text = tb

标签: c# wpf class initialization


【解决方案1】:

应该是(C#6):

HeaderTagControlsPair example = new HeaderTagControlsPair
{
     HeaderTextBlock = {Text = "test" }
};

【讨论】:

【解决方案2】:

您可以使用object initializer syntax 初始化(公共)字段或属性。在这种情况下,HeaderTextBlock 属性。但是您不能初始化这些类型的属性。所以你需要一个用于 Text 属性的嵌套对象初始化器。

要么:

HeaderTagControlsPair example = new HeaderTagControlsPair
{
    HeaderTextBlock = new TextBlock {Text = "test"}
};

在 C#6 中更短:

HeaderTagControlsPair example = new HeaderTagControlsPair
{
    HeaderTextBlock = { Text = "test" }
};

(我更喜欢第一个版本,以防止出现this 之类的奇怪问题)

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多