Is “if(!myobject)” the same as “if(myobject == null)”?

后端 未结 1 1331
失恋的感觉
失恋的感觉 2021-01-29 11:47

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)          


        
相关标签:
1条回答
  • 2021-01-29 12:02

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


    Based on this comment:

    myobject ... derives from MonoBehaviour.

    and this excerpt from the MonoBehavior docs:

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

    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#.

    0 讨论(0)
提交回复
热议问题