是"if(!myobject)"与"if(myobject == null)"相同吗? [英] Is "if(!myobject)" the same as "if(myobject == null)"?

查看:47
本文介绍了是"if(!myobject)"与"if(myobject == null)"相同吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我在Unity项目中遇到了一些有趣的C#代码:

Today I've come across an interesting bit of C# code in a Unity project:

MyScript ms = new MyScript(); //MyScript derives from MonoBehaviour
ms = null;
if(!ms) { Debug.Log("ms = "+(ms==null)); }

它的行为似乎与以下内容相同:

It does seem to behave the same as:

if(ms == null) { /*Do Stuff*/ }

但这真的是同一回事吗?我还没有找到关于此的任何文档.有没有理由不使用较短的版本,或者不喜欢使用另一个版本?

But is it really the same thing? I haven't found any documentation about this anywhere yet. Is there a reason to not use the shorter version or prefer one over the other?

推荐答案

否.您可以使用Javascript来实现,但是C#不能那样工作,除非myobject实际上是一个布尔值.

No. You can do that in Javascript, but C# doesn't work like that unless myobject is actually a boolean.

基于此评论:

myobject ...源自MonoBehaviour.

myobject ... derives from MonoBehaviour.

以及来自 MonoBehavior文档:

Operators

bool           Does the object exist?  
operator !=    Compares if two objects refer to a different object.  

您似乎可以对变量执行此操作,因为它可以隐式转换为bool.但是对于C#来说通常不行.

It looks like you can do this for your variable, becuase it is implicitly convertible to bool. But it's not generally okay for C#.

这篇关于是"if(!myobject)"与"if(myobject == null)"相同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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