我在进行代码审查时发现了一行,我们的一位开发人员正在使用这样的空对象初始值设定项创建一个对象:
List<Floorplan> floorplans = new List<Floorplan> { };
我不知道他为什么要这样实例化而不是:
List<Floorplan> floorplans = new List<Floorplan>();
使用空对象初始化器进行对象实例化有什么缺点吗?除了风格上不一致之外,我想知道是否有理由避免这种方法。有些东西告诉我这是气味,但我想在说任何话之前先确定一下。
最佳答案
编译结果相同
以下 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# 的一部分,我认为人们更习惯于构造函数语法。如果我遇到一些使用空集合初始值设定项的代码,我会想知道为什么,但它肯定没有任何严重的可读性问题。如果一个人足够聪明,完全可以理解代码,那么 {}
与 ()
不应该如此令人沮丧,以至于它会破坏一个人理解代码正在做什么的能力。这归结为一个见仁见智的问题。做你的团队一致同意的事情,如果只有你一个人,那就尽情使用吧。
关于c# - 使用空对象初始值设定项有什么缺点吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18022578/