空引用检查的良好做法是什么? [英] What is good practice for null reference checks?

查看:55
本文介绍了空引用检查的良好做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查对象上的空引用的最有效方法是什么?我见过各种代码示例,它们具有不同的检查方式,以下哪个是最有效的或被认为是最佳实践的?

What is the most efficient way to check for null references on objects? I have seen various code samples that have different ways of checking so of the following which is the most efficient or the one that it is considered best practice to use?

Object.ReferenceEquals(item, null)

item == null

item != null

Object.Equals(item, null)

谢谢

推荐答案

  1. Object.ReferenceEquals(item, null) 比较引用和等于 item == null.
  2. Object.Equals(item, null) 比较引用类型的引用和值类型的按位,但在反射器中它等于 (item == null) ||((item != null && null != null) && item.Equals(null)).
  3. item != null code 并不总是等于 !(item == null),但结果当然应该相等.
  4. item == null 代码不等于 null == item,它类似于 typeof(item).Equals(object)object.Equals(typeof(item)) 方法调用.
  1. Object.ReferenceEquals(item, null) compare references and equals to item == null.
  2. Object.Equals(item, null) compare references for reference types and bitwise for value types, but in reflector it's equal to (item == null) || ((item != null && null != null) && item.Equals(null)).
  3. item != null code not always equals to !(item == null), but of course result should be equal.
  4. item == null code not equals to null == item, it's similar to typeof(item).Equals(object) and object.Equals(typeof(item)) method calls.

它不同,因为您可以覆盖 !===Equals.使用已知实现的方法,null == item 编码更好,但更难阅读.Object.ReferenceEquals(null, item) 可能更快也可能更快.

It differ because you can override !=, ==, Equals. Use methods with known implementation, null == item is better to code, but harder to read. Object.ReferenceEquals(null, item) may be faster or not.

附言也使用 string.IsNullOrEmpty(item)

P.S. use string.IsNullOrEmpty(item) too

这篇关于空引用检查的良好做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆