检查:null 与 default()?
我想检查引用类型是否为空。我看到两个选项(_settings 是引用类型 FooType):
if (_settings == default(FooType)) { ... }
以及
if (_settings == null) { ... }
这两个选项的性能有何不同?
I want to check if a reference type is null. I see two options (_settings is of reference type FooType):
if (_settings == default(FooType)) { ... }
and
if (_settings == null) { ... }
How do these two perform differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
没有什么区别。任何引用类型的默认值都是
null
。default
关键字的 MSDN C# 参考页:https:// msdn.microsoft.com/en-us/library/25tdedf5.aspx。There's no difference. The default value of any reference type is
null
.MSDN's C# reference page for
default
keyword: https://msdn.microsoft.com/en-us/library/25tdedf5.aspx.现在我们不再需要将类型传递给默认值,默认值是首选。
它同样可读
它可以用于值类型和引用类型
它可以在泛型中使用
if (_settings == 默认) { ... }
另外,在调用之后
测试默认值而不是 null 更有意义。否则它应该是 FirstOrNull,但 value 没有空值,但有默认值。
Now that we don't need to pass the type to default anymore, default is preferred.
It is just as readable
It can be used both for value and reference types
It can be used in generics
if (_settings == default) { ... }
Also, after calling
it makes more sense to test for default after that and not for null. Otherwise it should have been FirstOrNull, but value dont have a null value but do have a default.
没有什么区别,但第二个更具可读性。使用
default
的最佳位置是处理泛型时。常见代码为return default(T);
There is no difference, but second one is more readable. The best place to use
default
is when you deal with generics. Common code isreturn default(T);
没有什么不同,但我认为
更清楚。
Not different but I think
is clearer.
我的理解是它们没有不同。仅当您处理值类型时它才重要。
My understanding is they are not different. It only matters when you are dealing with value types.
我肯定会进行针对 null 的特定检查。因为如果
_settings
类的类型发生变化,您可能会遇到引用问题。至少需要更改代码来破坏打开/关闭策略。这个IMO更安全、更清洁。
I would definitely go with the specific check against null. Because if the type of the
_settings
class ever changes you may run into reference issues. At minimum it would require a change to the code breaking the open/close policy.This IMO is safer and cleaner.
正如已经提到的,没有区别...但是您可能无论如何都想使用
default()
来处理的情况不是引用类型。通常这仅适用于泛型,但对于一般情况来说这是一个好习惯。As has been mentioned, there is no difference... but you might want to use
default(<type>)
anyway, to handle the cases where it's not a reference type. Typically this is only in generics, but it's a good habit to form for the general case.