如何从Type对象获取可空的Type对象

det*_*ale 1 .net c#

实现此方法的最佳方法是什么:

Type GetNullableTypeFromType(Type tp);
Run Code Online (Sandbox Code Playgroud)

以便

Type tpString = GetNullableTypeFromType(typeof(string));   // Returns typeof(string)
Type tpInt = GetNullableTypeFromType(typeof(int));   // Returns typeof(int?)
Run Code Online (Sandbox Code Playgroud)

RJ *_*han 10

public static Type GetNullableType(Type t)
{
    if (t.IsValueType && (Nullable.GetUnderlyingType(t) == null)) 
        return typeof(Nullable<>).MakeGenericType(t); 
    else
        return t;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你传递一个接口,这仍然会失败.您可以通过将方法体更改为类似的方式使其更加健壮:`if(t.IsValueType &&(Nullable.GetUnderlyingType(t)== null))返回typeof(Nullable <>).MakeGenericType(t); return t;` (2认同)