2016-08-26 40 views
1

私は非常に奇妙な問題があります。クラスの初期化中に 'コレクション初期化子で型を初期化できません'

ここで私が定義されたクラスです:私はそれを行うことはできません

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

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

は今、私はこのクラスのオブジェクトを作成し、それを初期化したいです。私はこれら3つのエラーを受け取ります:

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 

私は単純なオブジェクトの初期化を使用しています。私は間違って何をしていますか?

+0

は少なくとも1 'HeaderTextBlock'の' Text'プロパティに初期化せずにアクセスしたために起こります。 'HeaderTagControlsPair example = new HeaderTagControlsPair();'その後に個々の値を設定するか、 'test'文字列(例えば** tb **)を使って新しい' TextBlock'要素を宣言し、 'HeaderTextBlock.Text = tb'を代わりに宣言。 –

答えて

1

あなたはobject initializer syntaxで(パブリック)フィールドまたはプロパティを初期化することができます。この場合、HeaderTextBlockプロパティ。しかし、これらの型のプロパティを初期化することはできません。したがって、Textプロパティのネストされたオブジェクトイニシャライザが必要です。

このいずれか:C#6で

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

または短い:これらのエラーの

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

(私はthisのような奇妙な問題を防止するための最初のバージョンを好む)

2

それは(C#6)のようになります。

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

なぜですか?私はこのタイプの初期化を見たことがありませんでした。私はこれに続いた:https://msdn.microsoft.com/en-us/library/bb397680.aspx – Loreno

関連する問題