我一直在努力在我们的回购中重构一些旧的代码,我想到了一个想法。有几个地方使用if语句来确定某个属性或变量是否包含某个值,如果没有值,则为其分配一个值。然而,这些通常发生在长链中,并且有些笨重。
更换这样的东西是否有任何明显的上升空间或下行空间:
if (memo.DateTime == null)
{
memo.DateTime = DateTime.Now;
}
if (memo.dtoDate == null)
{
memo.dtoDate = DateTimeOffset.Now;
}
用这个:
memo.DateTime = memo.DateTime ?? DateTime.Now;
memo.dtoDate = memo.dtoDate ?? DateTimeOffset.Now;
答案 0 :(得分:2)
看起来像语法糖:
object test = Console.ReadLine();
if (test == null)
{
test = "default";
}
object test2 = Console.ReadLine() ?? "default";
IL发布中的
IL_0000: call string [mscorlib]System.Console::ReadLine()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: brtrue.s IL_000f
IL_0009: ldstr "default"
IL_000e: stloc.0
IL_000f: call string [mscorlib]System.Console::ReadLine()
IL_0014: dup
IL_0015: brtrue.s IL_001d
IL_0017: pop
IL_0018: ldstr "default"
IL_001d: stloc.1