开发者

Nullable types in .NET

开发者 https://www.devze.com 2023-02-21 01:16 出处:网络
protected static SqlParameter CreateParameter(string name, object value, bool skipEmpty, bool isOutput =false)
 protected static SqlParameter CreateParameter(string name, object value, bool skipEmpty, bool isOutput =false)
 {
    if (skipEmpty && value is string && string.IsNullOrEmpty((string)value))
        return null;
    //1
    if (skipEmpty && value is int? && value == null)
      return null;
    //2
    if (skipEmpty && value is Gu开发者_如何学Cid? && value == null)
      return null;
    //....................
}

The resharper says that 1 and 2 clauses are always false. But why?


If value is null then it is impossible to infer a type more complex than object from it, therefore it can never be int? or Guid?


if value is an object, and is null, what type was it? It doesn't have a type.

You've got a variable of type object, which doesn't contain anything. There's no way to know what someone else may have planned to place in that variable.


Or as the answer to C# get type of null object put it:

That's like asking what kind of cake would have been in an empty box with no label.


An is expression evaluates to true if the provided expression is non-null. Therefore, the expression (value is int? && value == null) always equals false


This should work:

if (skipEmpty && ((value is string && string.IsNullOrEmpty((string)value)) || value == null)) return null;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号