如何检测 C# 中的空引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/202630/
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 do I detect a null reference in C#?
提问by Fred
How do I determine if an object reference is null in C# w/o throwing an exception if it is null?
如何确定 C# 中的对象引用是否为空,如果为空则不抛出异常?
i.e. If I have a class reference being passed in and I don't know if it is null or not.
即如果我有一个类引用被传入,我不知道它是否为空。
采纳答案by Joel Coehoorn
What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block:
罗伯特所说的,但对于那个特殊情况,我喜欢用这样的保护子句来表达它,而不是将整个方法体嵌套在 if 块中:
void DoSomething( MyClass value )
{
if ( value == null ) return;
// I might throw an ArgumentNullException here, instead
value.Method();
}
回答by Patrick Desjardins
(YourObject != Null)
you can compare to null?
你可以比较null吗?
If it's null instead of throwing an exception you can initialize your object. You can use the Null Pattern.
如果它是 null 而不是抛出异常,您可以初始化您的对象。您可以使用空模式。
回答by Robert Paulson
testing against null will never* throw an exception
针对 null 的测试永远不会*抛出异常
void DoSomething( MyClass value )
{
if( value != null )
{
value.Method();
}
}
* never as in should never. As @Ilya Ryzhenkov points out, an incorrectimplementation of the != operator for MyClass could throw an exception. Fortunately Greg Beech has a good blog post on implementing object equality in .NET.
* never as in should never. 正如@Ilya Ryzhenkov 指出的那样,MyClass 的 != 运算符的错误实现可能会引发异常。幸运的是 Greg Beech 有一篇关于在 .NET 中实现对象相等性的好博文。
回答by milot
Or if you are using value types you can read about nullable types: http://www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx
或者,如果您使用值类型,您可以阅读有关可为空类型的信息:http: //www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx
回答by justin.m.chase
if(p != null)
{
DoWork(p);
}
Also, the 'as' keyword is helpful if you want to detect if a class is of the right type and use it all at once.
此外,如果您想检测一个类是否是正确的类型并一次性使用它,'as' 关键字很有用。
IExample e = p as IExample;
if(e != null)
DoWork(e);
In the above example if you were to cast e like (IExample)e it will throw an exception if e does not implement IExapmle. If you use 'as' and e doesn't implement IExample e will simply be null.
在上面的例子中,如果你像 (IExample)e 这样转换 e,它会在 e 没有实现 IExapmle 时抛出一个异常。如果您使用 'as' 并且 e 没有实现 IExample,e 将简单地为 null。
回答by Fred
I have in the application's xaml.cs application derivative definition:
我在应用程序的 xaml.cs 应用程序衍生定义中有:
private SortedList myList;
And I want to be able to re-use my constructors. So I needed:
我希望能够重用我的构造函数。所以我需要:
if ( myList == null)
myList = new SortedList();
Thanks Robert!
谢谢罗伯特!
回答by Ilya Ryzhenkov
Note, that having operator != defined on MyClass would probably lead do different result of a check and NullReferenceException later on. To be absolutely sure, use object.ReferenceEquals(value, null)
请注意,在 MyClass 上定义 operator != 可能会导致稍后执行不同的检查结果和 NullReferenceException。为了绝对确定,请使用 object.ReferenceEquals(value, null)
回答by Jason V
It's nit picky, but I always code these like ...
它很挑剔,但我总是像这样编写代码......
if (null == obj) {
obj = new Obj();
}
instead of
代替
if (obj == null) {
obj = new Obj();
}
to avoid accidently writing
以免误写
if (obj = null) {
obj = new Obj();
}
because
因为
if (null = obj) {
obj = new Obj();
}
will give you a compiler error
会给你一个编译器错误
回答by Mark Ingram
If you look in the majority of the .NET framework source code you will see they put checks like this at the top of their functions.
如果您查看大部分 .NET 框架源代码,您会看到它们将这样的检查放在其函数的顶部。
public void DoSomething(Object myParam)
{
if (myParam == null) throw new ArgumentNullException("myParam");
// Carry on
}
回答by James Harcourt
With C# 6.0 this is much more elegant; you can do it in one line :-)
在 C# 6.0 中,这更加优雅;你可以在一行中完成:-)
value?.Method();
If "value" is null, nothing will happen - and no exception.
如果“value”为空,则什么都不会发生——也不例外。