《刻意練習之C#》-0007- 可為空引用型別
阿新 • • 發佈:2020-06-02
NullReferenceException的困擾
實際專案開發過程中,我們經常會遇到空引用錯誤:
Solution solution = null; var result = solution.TwoSumOne(nums,13); // 會報以下錯誤 Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
一般的做法是:
在訪問例項成員前,先對例項成員進行判空處理。
if(null != solution) { var result = solution.TwoSumOne(nums,13); }
如果能在編譯時候,就能檢查出來可能得空引用,豈不更好?
nullable reference type
C# 8.0引入可為空引用型別(nullable reference types)和非空引用型別(non-nullable reference types)。
-
nullable reference type
string? name;
-
型別後面不帶?的變數,都為non-nullable reference type
啟用空引用型別
在專案的csproj檔案加入一行:
<Nullable>enable</Nullable>
針對程式碼:
Solution solution = null; var result = solution.TwoSumOne(nums,13);
編譯後,可以看到編譯器會產生兩個警告:
Program.cs(13,33): warning CS8600: Converting null literal or possible null value to non-nullable type. [/Users/zclmoon/myProjects/algorithm/csharp/TwoSum01/TwoSum.csproj]Program.cs(15,26): warning CS8602: Dereference of a possibly null reference. [/Users/zclmoon/myProjects/algorithm/csharp/TwoSum01/TwoSum.csproj]