简体   繁体   English

如何在C#中检测空引用?

[英]How do I detect a null reference in C#?

How do I determine if an object reference is null in C# w/o throwing an exception if it is null? 如何在C#中确定对象引用是否为空?如果它为null,则抛出异常?

ie If I have a class reference being passed in and I don't know if it is null or not. 即如果我传入了类引用,我不知道它是否为null。

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 incorrect implementation of the != operator for MyClass could throw an exception. 正如@Ilya Ryzhenkov指出的那样,MyClass的!=运算符的错误实现可能会引发异常。 Fortunately Greg Beech has a good blog post on implementing object equality in .NET . 幸运的是,Greg Beech有一篇关于在.NET中实现对象相等性的博文。

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: Robert说的是什么,但是对于那个特例,我喜欢用这样的保护子句表达它,而不是将整个方法体嵌套在if块中:

void DoSomething( MyClass value )
{
    if ( value == null ) return;
    // I might throw an ArgumentNullException here, instead

    value.Method();
}

Note, that having operator != defined on MyClass would probably lead do different result of a check and NullReferenceException later on. 注意,在MyClass上定义运算符!=可能会导致检查结果不同,以及稍后会发生NullReferenceException。 To be absolutely sure, use object.ReferenceEquals(value, null) 要绝对确定,请使用object.ReferenceEquals(value,null)

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. 在上面的例子中,如果你要像e(IExample)那样投射e,如果e没有实现IExapmle,它将抛出异常。 If you use 'as' and e doesn't implement IExample e will simply be null. 如果你使用'as'而e没有实现IExample e将只是null。

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
}

With C# 6.0 this is much more elegant; 使用C#6.0,这更加优雅; you can do it in one line :-) 你可以在一行中做到:-)

value?.Method();

If "value" is null, nothing will happen - and no exception. 如果“value”为null,则不会发生任何事情 - 也不例外。

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 会给你一个编译错误

(YourObject != Null)

you can compare to null? 你可以比较null吗?

If it's null instead of throwing an exception you can initialize your object. 如果它为null而不是抛出异常,则可以初始化对象。 You can use the Null Pattern. 您可以使用Null Pattern。

或者,如果您使用值类型,则可以阅读有关可空类型的内容: http//www.c-sharpcorner.com/UploadFile/mosessaur/nullabletypes08222006164135PM/nullabletypes.aspx

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! 谢谢罗伯特!

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

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