如何确定对象引用是否为空? [英] How to determine whether object reference is null?

查看:246
本文介绍了如何确定对象引用是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定对象引用变量是否为null的最佳方法是什么?

What is the best way to determine whether an object reference variable is null?

是下面的吗?

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 
} 

顺便说一句:您的代码无法像现在那样编译,因为myObjVar在初始化之前就已被访问.

BTW: Your code wouldn't compile the way it is now, because myObjVar is accessed before it is being initialized.

这篇关于如何确定对象引用是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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