C# 如何判断对象引用是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12000228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine whether object reference is null?
提问by CJ7
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
}
采纳答案by Daniel Hilgarth
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 myObjVaris accessed before it is being initialized.
顺便说一句:你的代码不会像现在这样编译,因为myObjVar在它被初始化之前就被访问了。
回答by Habib
The way you are doing is the best way
你的方式是最好的方式
if (myObjVar == null)
{
// do stuff
}
but you can use null-coalescing operator??to check, as well as assign something
但您可以使用空合并运算符??来检查,以及分配一些东西
var obj = myObjVar ?? new MyObject();
回答by Habib Zare
you can:
你可以:
MyObject myObjVar = MethodThatMayOrMayNotReturnNull();
if (if (Object.ReferenceEquals(null, myObjVar))
{
// do stuff
}
回答by smhnkmr
You can use Object.ReferenceEquals
您可以使用 Object.ReferenceEquals
if (Object.ReferenceEquals(null, myObjVar))
{
.......
}
This would return true, if the myObjVar is null.
如果 myObjVar 为空,这将返回 true。

