如何从 Type 对象获取可为 null 的类型对象
本文关键字:对象 null 类型 获取 Type | 更新日期: 2023-09-27 18:35:11
实现此方法的最佳方法是什么:
Type GetNullableTypeFromType(Type tp);
因此
Type tpString = GetNullableTypeFromType(typeof(string)); // Returns typeof(string)
Type tpInt = GetNullableTypeFromType(typeof(int)); // Returns typeof(int?)
public static Type GetNullableType(Type t)
{
if (t.IsValueType && (Nullable.GetUnderlyingType(t) == null))
return typeof(Nullable<>).MakeGenericType(t);
else
return t;
}