了解.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中文網其他相關文章!