我正在进行代码审查,并找到一条线,我们的一个开发人员使用这样的空对象初始化器创建一个对象:
List<Floorplan> floorplans = new List<Floorplan> { };
Run Code Online (Sandbox Code Playgroud)
我不知道为什么他会以这种方式实例化而不是:
List<Floorplan> floorplans = new List<Floorplan>();
Run Code Online (Sandbox Code Playgroud)
使用空对象初始化器对象实例化有任何缺点吗?除了在风格上不一致之外,我想知道是否有理由避免这种方法.有东西告诉我这种气味,但我想在我说什么之前确定.
Dan*_*Dan 10
编译结果是一样的.
以下C#:
static void Main()
{
var x = new List<int>();
var y = new List<int> { };
}
Run Code Online (Sandbox Code Playgroud)
编译成以下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
Run Code Online (Sandbox Code Playgroud)
如果您向集合添加值:
static void Main()
{
var x = new List<int>();
x.Add(1);
var y = new List<int> { 1 };
}
Run Code Online (Sandbox Code Playgroud)
这是由此产生的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
Run Code Online (Sandbox Code Playgroud)
这显示了集合初始化程序只是语法糖.因为集合初始化器最初不是C#的一部分,所以我认为人们更习惯于构造函数语法.如果我遇到一些使用空集合初始化程序的代码,我会想知道为什么,但它肯定没有任何严重的可读性问题.如果一个人足够聪明地理解代码,那么{}vs ()不应该如此沮丧,以至于它破坏了一个人理解代码正在做什么的能力.这归结为意见问题.做你的团队同意的事情,如果只是你,那就把它用在心里.