簡體   English   中英

C# LinkedList:可能是 null 引用錯誤?

[英]C# LinkedList: Possible null reference error?

我正在嘗試學習 C# 的一些基礎知識(一般來說對編程來說並不陌生),但我無法使 LinkedList 的某些代碼正常工作。 具體來說,當我將一個值從 LinkedList 分配給 LinkedListNode 變量時,我收到了一個“可能的 null 參考”錯誤——這不可能嗎? 我從網站 ( https://dev.to/adavidoaiei/fundamental-data-structures-and-algorithms-in-c-4ocf ) 上獲取了代碼,所以我覺得代碼完全錯誤似乎很奇怪。

這是導致問題的代碼部分:

    // Create the linked list
    string[] words = 
        { "the", "fox", "jumps", "over", "the", "dog" };
    LinkedList<string> sentence = new LinkedList<string>(words);
    Display(sentence, "The linked list values:");
    Console.WriteLine("sentence.Contains(\"jumps\") = {0}",
        sentence.Contains("jumps"));

    // Add the word 'today' to the beginning of the linked list
    sentence.AddFirst("today");
    Display(sentence, "Test 1: Add 'today' to beginning of the list:");

    // Move the first node to be the last node
    LinkedListNode<string> mark1 = sentence.First;
    sentence.RemoveFirst();
    sentence.AddLast(mark1);
    Display(sentence, "Test 2: Move first node to be last node:");

初始化變量“mark1”時,出現“可能的 null 引用錯誤”:

LinkedListNode<string> mark1 = sentence.First;

我正在嘗試做的事情是否完全可行,或者這是使用 LinkedList 的完全錯誤的方式?

查看ListedList<T>.First屬性的簽名:

public System.Collections.Generic.LinkedListNode<T>? First { get; }

看到那個問號了嗎? 這意味着該值可以是 null。

您收到的警告(這是警告,不是錯誤)告訴您,當您 go 讀取First屬性時,它可能具有 null 值,並且您可能將 null 值分配給不應該具有的值分配給它的 null 值。

現在,不幸的是,當前的 c# 編譯器不夠聰明,無法識別像這樣的東西不能有null ,例如:

LinkedList<string> sentence = new LinkedList<string>();
sentence.AddFirst("today");
string a = sentence.First.Value;
// last line will have a warning for "sentence.First" possibly being null.

解決此問題的三個選項。

  1. “我知道得更多”。 在編譯器認為可能是 null 的東西之后使用“空寬恕”運算符 ( ! ) 以強制它始終將其視為非空。

     string a = sentence.First.;Value;
  2. “核實”。 事先做一個簡單的 null 檢查。

     if (sentence.First is not null) string a = sentence.First.Value;
  3. 禁用可為空的引用類型功能。 我真的不推薦這個。


另外,一般警告:所有這些都是編譯時檢查 程序運行時沒有null檢查/執行的權力。 程序運行時,可以將標記為“不可為空”的變量設置為 null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM