簡體   English   中英

不可實例化的密封 class 中可能出現 NullReferenceException

[英]Possible NullReferenceException in a non-instantiatable sealed class

考慮到以下幾點:

public sealed class RequestType
{
    private RequestType()
    {
    }

    private RequestType(string value)
    {
        Value = value;
    }

    private string Value { get; }

    public static RequestType Get => new RequestType("GET");
    public static RequestType Post => new RequestType("POST");
    public static RequestType Put => new RequestType("PUT");
    public static RequestType Head => new RequestType("HEAD");
    public static RequestType Delete => new RequestType("DELETE");
    public static RequestType Patch => new RequestType("PATCH");
    public static RequestType Options => new RequestType("OPTIONS");

    ....

    public static bool operator ==(RequestType r, string o)
    {
        return r.Equals(o.ToUpperInvariant());
    }

    ....
}

我在RequestTypeobject上都收到了Possible NullReferenceException objectnull的可能性是正確的,但它不適用於RequestType ,因為所有屬性都已經預定義並且顯然無法實例化它。

那么,在這種情況下應該采取什么正確的行動呢? 無論如何檢查 null 是一種好習慣嗎?

所有屬性都已預定義,無法實例化

無關緊要

RequestType 不能是 null

對於要為 null 的參數,您不需要實例化它(為 null 與此完全相反。)。 您只需編寫null ,並且擁有“預定義”實例並不會阻止人們這樣做。 除非您使用值類型,例如枚舉,否則您無法阻止人們這樣做。

例如,這將使您的代碼拋出 NRE,即使您在o上添加了 null 檢查:

((RequestType)null) == "some string"

所以是的,你仍然應該檢查空值。

暫無
暫無

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

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