如题,在C#/.NET/.NET Core应用程序编程开发中,如何检测一个对象是否为可空类型(nullable)呢?
Rector
2020-02-08 提问
public bool IsNullable(object obj) { Type t = obj.GetType(); return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>); }
2020-02-08 回答
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; }
static bool IsNullable<T>(T obj) { return default(T) == null; }
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<>); }
码龄: 3176天
专注.NET/.NET Core