不可实例化的密封 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());
}
....
}
我在 RequestType
和 object
上都收到了 Possible NullReferenceException
。 object
是 null
的可能性是正确的,但它不适用于 RequestType
,因为所有属性都已经预定义,显然无法实例化它。
那么,在这种情况下,正确的做法应该是什么?无论如何检查 null 是好习惯吗?
all properties are already pre-defined and there's no way of instantiating it
与
无关
RequestType can't be null
对于为空的参数,您不需要实例化它(为空与此完全相反!)。您只需编写 null
,拥有“预定义”实例根本不会阻止人们这样做。你不能阻止人们这样做,除非你使用值类型,比如枚举。
例如,即使您在 o
:
上添加了空检查,这也会使您的代码抛出 NRE
((RequestType)null) == "some string"
所以是的,您仍然应该检查空值。
考虑以下因素:
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());
}
....
}
我在 RequestType
和 object
上都收到了 Possible NullReferenceException
。 object
是 null
的可能性是正确的,但它不适用于 RequestType
,因为所有属性都已经预定义,显然无法实例化它。
那么,在这种情况下,正确的做法应该是什么?无论如何检查 null 是好习惯吗?
all properties are already pre-defined and there's no way of instantiating it
与
无关RequestType can't be null
对于为空的参数,您不需要实例化它(为空与此完全相反!)。您只需编写 null
,拥有“预定义”实例根本不会阻止人们这样做。你不能阻止人们这样做,除非你使用值类型,比如枚举。
例如,即使您在 o
:
((RequestType)null) == "some string"
所以是的,您仍然应该检查空值。