c# - 哪个更好?强制转换可为 null 的类型或使用 Value 属性检索值?

标签 c# .net nullable

一种方式比另一种方式有性能优势吗?

是否有其他理由选择其中之一?

最佳答案

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/

相关文章:

c# - 回发时复选框状态重置

c# - 自托管服务上的 WCF Streaming 大数据 (500MB/1GB)

db2 - 启用数据捕获后,使DB2中的列可为空

c# - 如何在父窗口关闭时关闭子窗口? (WPF)

c# - 此特定场景中的最佳缓存策略

c# - String.Contains() 比 String.IndexOf() 快吗?

c# - 如果不为空则添加到集合

c# - Nullable<int> 到 Int 错误

c# - 如何使用 N 的参数从 C# 更新 MS Access 中的前 N ​​行?

c# - 如何使用不同分辨率的图像将矩形从一个图像复制到另一个图像