簡體   English   中英

將null傳遞給方法時的編譯時錯誤

[英]Compile time error when passing null to a method

無論如何,要避免將null傳遞給方法。

就像是:

   public static string Add([not null] string word1 , string word2)
        {
            return word1 + word2;
        }
![enter image description here][1]
string sentence = Add(null, "world");
                       ^^ compile error

不會。編譯器不是很通心的。 在某些情況下,編譯器根本無法推斷將要提前傳遞的內容。

考慮以下內容,以及編譯器可能如何保護您...

var rnd = new Random();
Foo(rnd.Next(2) == 0 ? "foo" : null);

由於字符串是引用類型,因此無法在編譯時進行檢查。 常見且有用的事情是檢查運行時並拋出ArgumentNullException。 該方法的用戶將以錯誤的方式使用它,因此將立即捕獲異常。

例如:

public static string Add(string word1, string word2)
{
    if (word1 == null) throw new ArgumentNullException("word1");

    return word1 + word2;
}

如果您希望達到與示例相似的語法,則可以使用PostSharp代碼合同。 免費版本允許您在每個項目中最多使用10個此類屬性,請查看示例PostSharp代碼合同示例 它不會給您編譯器錯誤,但會簡化代碼。

暫無
暫無

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

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