一种方式比另一种方式有性能优势吗?
是否有其他理由选择其中之一?
最佳答案
Is there a performance benefit to one way over the other?
没有。它们都编译为完全相同的 IL。强制转换是 Value 属性的语法糖。这段代码:
int? x = null;
Console.WriteLine(x.Value);
Console.WriteLine((int)x);
编译为这些 IL 指令,忽略 nop
:(您可以使用 ildasm、ILSpy、DotPeek 等自行测试)
// int? x = null;
ldloca.s 0
initobj valuetype [mscorlib]System.Nullable`1<int32>
// Console.WriteLine(x.Value);
ldloca.s 0
call instance !!0 [mscorlib]System.Nullable`1<int32>::get_Value()
call void [mscorlib]System.Console::WriteLine(int32)
// Console.WriteLine((int)x);
ldloca.s 0
call instance !!0 [mscorlib]System.Nullable`1<int32>::get_Value()
call void [mscorlib]System.Console::WriteLine(int32)
Are there other reasons to choose one over the other?
我宁愿尽可能避免转换,因为它们总是有可能与实际类型不同步。如果我将我的变量从 int?
更改为 byte?
,那么我所有的转换都是错误的——但是如果我使用的是 .Value
,我我可以根据需要自由更改变量。对我来说,硬转换在可读性方面没有增加任何东西,但在可维护性方面确实有成本。
关于c# - 哪个更好?强制转换可为 null 的类型或使用 Value 属性检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7116342/