創建列表有從初始
var list = new List<UserType>
{
new UserType(...),
new UserType(...),
};
和
var list = new List<UserType>()
{
new UserType(...),
new UserType(...),
};
之間有什麼區別?
以前我總是用第二個想,我只是需要調用列表中的無參數(或任何其他)構造函數...
創建列表有從初始
var list = new List<UserType>
{
new UserType(...),
new UserType(...),
};
和
var list = new List<UserType>()
{
new UserType(...),
new UserType(...),
};
之間有什麼區別?
以前我總是用第二個想,我只是需要調用列表中的無參數(或任何其他)構造函數...
不,沒有區別。生成的IL是正是相同:
IL_0001: newobj System.Collections.Generic.List<UserQuery+UserType>..ctor
IL_0006: stloc.1 // <>g__initLocal0
IL_0007: ldloc.1 // <>g__initLocal0
IL_0008: newobj UserQuery+UserType..ctor
IL_000D: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
IL_0012: nop
IL_0013: ldloc.1 // <>g__initLocal0
IL_0014: newobj UserQuery+UserType..ctor
IL_0019: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
IL_001E: nop
IL_001F: ldloc.1 // <>g__initLocal0
IL_0020: stloc.0 // list
即使實例化一個新的List
並調用.Add
自己頗爲相似,即:
var list = new List<UserType>();
list.Add(new UserType());
list.Add(new UserType());
...生成:
IL_0001: newobj System.Collections.Generic.List<UserQuery+UserType>..ctor
IL_0006: stloc.0 // list
IL_0007: ldloc.0 // list
IL_0008: newobj UserQuery+UserType..ctor
IL_000D: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
IL_0012: nop
IL_0013: ldloc.0 // list
IL_0014: newobj UserQuery+UserType..ctor
IL_0019: callvirt System.Collections.Generic.List<UserQuery+UserType>.Add
略有不同 - 看起來差異在於生成一個臨時變量並將其賦值到list
直接創建和操作list
。
感謝您的詳細信息。 – sharpener
我編輯了你的標題。請參閱:「[應該在其標題中包含」標籤「](http://meta.stackexchange.com/questions/19190/)」,其中的共識是「不,他們不應該」。 –
像ReSharper這樣的工具會通知您,當使用初始化器時可以刪除'()'。假設你沒有參數。 – Logarr
好的,對不起。 – sharpener