首页 / 问答 / C#/.NET/.NET Core应用程序编程开发中如何检测一个对象是否为可空类型(nullable)?

C#/.NET/.NET Core应用程序编程开发中如何检测一个对象是否为可空类型(nullable)?

.NET C# .NET Core 1.74K 次浏览
0

如题,在C#/.NET/.NET Core应用程序编程开发中,如何检测一个对象是否为可空类型(nullable)呢?

回复 [×]
提交评论
请输入评论内容

4 个回答

  • 1
    public bool IsNullable(object obj)
    {
        Type t = obj.GetType();
        return t.IsGenericType
            && t.GetGenericTypeDefinition() == typeof(Nullable<>);
    }
    
    Rector的个人主页

    Rector

    2020-02-08 回答

    • 0
      static bool IsNullable<T>(T obj)
      {
          if (obj == null) return true;
          Type type = typeof(T);
          if (!type.IsValueType) return true;
          if (Nullable.GetUnderlyingType(type) != null) return true;
          return false;
      }
      
      Rector的个人主页

      Rector

      2020-02-08 回答

      • 0
        static bool IsNullable<T>(T obj)
        {
            return default(T) == null;
        }
        
        Rector的个人主页

        Rector

        2020-02-08 回答

        • 0
          public static bool IsObjectNullable<T>(T obj)
              {
                  Type argType = typeof(T);
                  if (!argType.IsValueType || obj == null)
                      return true;
                  return argType.IsGenericType && argType.GetGenericTypeDefinition() == typeof(Nullable<>);
              }
          
          Rector的个人主页

          Rector

          2020-02-08 回答

          我来回答