如何确定对象引用是否为空?
问题描述:
确定对象引用变量是否为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.