了解.net
中的nullReferenceExceptions 当您的代码试图访问当前拥有a>值的参考变量的成员(属性,方法等)时,就会出现NullReferenceException
。 通常,当尚未初始化变量或方法出乎意料地返回时,这通常会发生。null
>。
null
>非初始化的变量:
null
访问嵌套属性(例如,objectA.objectB.propertyC
objectA
有效的调试策略:objectB
null
战略断点:>在您的代码中的关键点执行,以检查变量值并确定
null
>
2。默认值:提供默认值,以防参考可能为
>:>
null
<code class="language-csharp">void PrintName(Person p) { if (p != null) Console.WriteLine(p.Name); }</code>3。自定义异常:
>通过抛出更有信息的自定义异常来处理电位
>值
null
<code class="language-csharp">string GetCategory(Book b) { return b?.Category ?? "Unknown"; //Null-conditional operator and null-coalescing operator }</code>)和null-条件成员访问(
):
null
<code class="language-csharp">string GetCategory(string bookTitle) { var book = library.FindBook(bookTitle); if (book == null) throw new BookNotFoundException(bookTitle); return book.Category; }</code>5。 null上下文(C#8及以后):
?.
利用零上下文功能在编译时强制执行更严格的空检查。?[]
FirstOrDefault()
>,它可以返回SingleOrDefault()
。
null
GetValueOrDefault()
事件:以上是是什么导致NullReferenceExceptions,如何在.NET中避免它们?的详细内容。更多信息请关注PHP中文网其他相关文章!