代码之家  ›  专栏  ›  技术社区  ›  Explisam

不可实例化的密封类中可能存在NullReferenceException

  •  0
  • Explisam  · 技术社区  · 4 年前

    考虑到以下几点:

    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());
        }
    
        ....
    }
    

    我收到了 Possible NullReferenceException RequestType object 对象 存在 null 是真的,但不是为了 请求类型 因为所有的属性都已经被预先定义好了,显然没有办法实例化它。

    那么,在这种情况下应该采取什么样的正确行动呢?检查空值是一种好的做法吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Sweeper    4 年前

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

    与…无关

    RequestType不能为空

    null ,而拥有“预定义”实例并不能阻止人们这么做。除非使用值类型(如枚举),否则无法阻止人们这样做。

    例如,这将使您的代码抛出一个NRE,即使您在 o :

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

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