简体   繁体   English

如何确定对象引用是否为空?

[英]How to determine whether object reference is null?

What is the best way to determine whether an object reference variable is null ? 确定对象引用变量是否为null的最佳方法是什么?

Is it the following? 是以下吗?

MyObject myObjVar = null;
if (myObjVar == null)
{
    // do stuff
}

Yes, you are right, the following snippet is the way to go if you want to execute arbitrary code: 是的,你是对的,如果你想执行任意代码,下面的代码片段是要走的路:

MyObject myObjVar; 
if (myObjVar == null) 
{ 
    // do stuff 
} 

BTW: Your code wouldn't compile the way it is now, because myObjVar is accessed before it is being initialized. 顺便说一下:你的代码不会像现在这样编译,因为myObjVar在初始化之前就被访问了。

The way you are doing is the best way 你的方式是最好的方式

if (myObjVar == null)
{
    // do stuff
}

but you can use null-coalescing operator ?? 但你可以使用null-coalescing运算符 ?? to check, as well as assign something 检查,以及分配一些东西

var obj  = myObjVar ?? new MyObject();

You can use Object.ReferenceEquals 您可以使用Object.ReferenceEquals

if (Object.ReferenceEquals(null, myObjVar)) 
{
   ....... 
} 

This would return true, if the myObjVar is null. 如果myObjVar为null,则返回true。

you can: 您可以:

MyObject myObjVar = MethodThatMayOrMayNotReturnNull();
if (if (Object.ReferenceEquals(null, myObjVar)) 
{
    // do stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM