我应该检查对象是否为空的第一或第二? [英] Should I check to see if an object is null first or second?

查看:102
本文介绍了我应该检查对象是否为空的第一或第二?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如说我创建一个鸭

Duck myDuck = DuckFactory.CreateDuck();

在过去我一直检查,看看是否myDuck为null

In the past I've always check to see if myDuck is null

if (myDuck == null)
{
  // Do stuff
}

我最近看了一些代码,对于空先检查。

I've recently looked at some code that check for null first.

if (null == myDuck)
{
   // Do stuff
}

在我看来,这些都是一样的,但是否有这两个之间的差异?是否有一个比其他任何性能优势?是否有检查,如果一个对象为空建议的最佳实践?

It seems to me that these are the same, but are there any differences between these two? Is there any performance benefits to one over the other? Is there a recommended best practice for checking if an object is null?

推荐答案

第二个从C / C茎++(和其他地方)如果这是一个有效的结构

The second stems from C/C++ (and elsewhere) where this is a valid construct

if (myDuck = null) {
}

这不是在C#有效(除非您的表达式解析为一个布尔)。例如,这是有效的C#

That's not valid in C# (unless your expression resolves to a boolean). For example, this is valid C#

bool b = ...
if (b = true) {
}

把恒首先是防守阻止意外分配当你想要比较。我会说更多的人把变量的左侧,但并没有什么错把不断给留着。

Putting the constant first was defensive to stop accidental assignment when you wanted comparison. I'd say more people put the variable to the left but there is nothing wrong with putting the constant to the left either.

随便挑一个,是它保持一致。

Just pick one and be consistent about it.

这篇关于我应该检查对象是否为空的第一或第二?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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