【问题标题】:Possible NullReferenceException in a non-instantiatable sealed class不可实例化的密封类中可能出现 NullReferenceException
【发布时间】:2021-05-16 09:38:24
【问题描述】:

考虑以下几点:

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 NullReferenceExceptionobjectnull 的可能性是正确的,但它不适用于 RequestType,因为所有属性都已经预定义并且显然无法实例化它。

那么,在这种情况下应该采取什么正确的行动?无论如何检查 null 是一种好习惯吗?

【问题讨论】:

    标签: c# null


    【解决方案1】:

    所有属性都已预定义,无法实例化

    无关

    RequestType 不能为空

    对于为空的参数,您不需要实例化它(为空是完全相反的!)。您只需编写null,并且拥有“预定义”实例并不会阻止人们这样做。除非您使用值类型,例如枚举,否则您无法阻止人们这样做。

    例如,这将使您的代码抛出 NRE,即使您在 o 上添加了空检查:

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

    所以是的,您仍然应该检查空值。

    【讨论】:

    • 哦~好吧,所以,为了使它不可为空,我应该改用struct,对吧?但是,这将使实例化它成为可能。有没有办法避免这两种情况?
    • @Explisam 嗯,我想不出任何真正的好主意。您的类型当然应该是值类型,但 C# 值类型需要一个“0”值,而您的类型缺少该值...无论如何,请尝试 answer 末尾的 _isValid 解决方案。您实际上不需要检查== 中的_isValid 标志,因为Value 将为空,并且无论如何比较总是错误的,因为您已经检查了o 是否为空。
    • 如果我使用_isValid 来解决它,我晚上不会睡觉。我只会抛出一个空异常。我只是希望有一个设计时错误类型的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2012-07-12
    • 2012-10-15
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2021-10-26
    相关资源
    最近更新 更多