コンパイル結果は同じです。
次のC#:
static void Main()
{
var x = new List<int>();
var y = new List<int> { };
}
は、次のILにコンパイル:
.method private hidebysig static
void Main() cil managed
{
// Method begins at RVA 0x2050
// Code size 14 (0xe)
.maxstack 1
.entrypoint
.locals init (
[0] class [mscorlib]System.Collections.Generic.List`1<int32> x,
[1] class [mscorlib]System.Collections.Generic.List`1<int32> y
)
IL_0000: nop
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_0006: stloc.0
IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_000c: stloc.1
IL_000d: ret
} // end of method Program::Main
あなたがコレクションに値を追加する場合:
static void Main()
{
var x = new List<int>();
x.Add(1);
var y = new List<int> { 1 };
}
これは結果としてILあります。
.method private hidebysig static
void Main() cil managed
{
// Method begins at RVA 0x2050
// Code size 32 (0x20)
.maxstack 2
.entrypoint
.locals init (
[0] class [mscorlib]System.Collections.Generic.List`1<int32> x,
[1] class [mscorlib]System.Collections.Generic.List`1<int32> y,
[2] class [mscorlib]System.Collections.Generic.List`1<int32> '<>g__initLocal0'
)
IL_0000: nop
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: ldc.i4.1
IL_0009: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::Add(!0)
IL_000e: nop
IL_000f: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldc.i4.1
IL_0017: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::Add(!0)
IL_001c: nop
IL_001d: ldloc.2
IL_001e: stloc.1
IL_001f: ret
} // end of method Program::Main
これは、コレクション初期化子がのみシンタックスシュガーであるかを示しています。コレクションの初期化子はもともとC#の一部ではなかったので、私は人がコンストラクタの構文に慣れていると思います。空のコレクションイニシャライザを使用したコードに遭遇した場合、私は自分自身に不思議に思うでしょうが、確かに重大な可読性の問題はありません。コードを理解するのに十分な知能があれば、{}
と()
は、コードが何をしているのかを理解する能力を損なうことがありません。それは意見の問題になる。あなたのチームが同意したことを行い、それがあなただけのものなら、それをあなたの心のコンテンツに使用します。
出典
2013-08-02 17:41:48
Dan
'var floorplans = new List();'は最高のIMOです。欠点はありません。 –
疑問がある場合はILを確認してください。コレクション初期化子は構文的な砂糖だけです。 –
FYI - ReSharperは、デフォルトでは、空のオブジェクトイニシャライザに対して警告を発生します。 –