簡體   English   中英

那些額外的花括號在C#中做什么?

[英]What are those extra curly brackets doing in C#?

我不知道如何搜索這個問題; 如果它是多余的,請原諒我。

所以,我有一些像這樣的代碼:

textBox1.InputScope = new InputScope { Names = { _Scope } };

Names屬性的類型為IList

我的代碼是在列表中添加項目還是創建新列表?

額外的花括號是做什么的?

這是一個集合初始值設定項 ,但是沒有創建新集合 - 它只是添加到現有集合中。 它被用來作為構件-初始化物體初始化初始化值部分。 它相當於:

InputScope tmp = new InputScope();
tmp.Names.Add(_Scope);
textBox1.InputScope = tmp;

有關詳細信息,請參閱C#4規范的7.6.10.3節。

這是一個集合初始化程序 它允許您將項添加到Names集合中。

new InputScope { // indicates an object-initializer for InputScope using
                 // the default constructor
   Names = { // indicates an in-place usage of a collection-initializer
     _Scope  // adds _Scope to Names
   } // ends the collection-initializer
}; // ends the object-initializer

var tmp = new InputScope();
tmp.Names.Add(_Scope);
textBox1.InputScope = tmp;

第一個大括號集是對象初始值設定項。 第二組是名稱 (集合)的IList

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM