c# - 初始化我的类的对象时“无法使用集合初始化程序初始化类型”

标签 c# wpf class initialization

我有一个很奇怪的问题。

这是我定义的类:

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

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

最佳答案

应该是(C#6):

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

关于c# - 初始化我的类的对象时“无法使用集合初始化程序初始化类型”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39163123/

相关文章:

java - 为什么不显示此 Swing 选项卡式 Pane ?

javascript - 反射(reflect)后退/前进类(class)的变化

c# - 如何对在 MVVM 中调用异步方法的 DelegateCommand 进行单元测试

c# - 文本框 SelectAll 无法正常工作

c# - 如何访问 Azure Function 2 中的 Azure 服务总线消息属性

wpf - 在 ListView 中的项目之间绘制插入符号

c# - 仅用于 ListViewItem 的上下文菜单

c# - 为什么类数组消耗的内存比结构数组多 20%?

c# - 带有 char * 参数的 DLLImport。只有一个字符被传递

c# - 在 Windows 窗体 C# 上打开 Word (.docx) 文件