如何将非可空类型转换为可空类型?

时间:2011-10-20 13:16:23

标签: c# reflection nullable

是否可以将仅在运行时知道的非可空值类型转换为可空?换句话说:

public Type GetNullableType(Type t)
{
    if (t.IsValueType)
    {
        return typeof(Nullable<t>);
    }
    else
    {
        throw new ArgumentException();
    }
}

显然,return行会出错。有没有办法做到这一点? Type.MakeGenericType方法看起来很有希望,但我不知道如何获得代表Type的未指定的通用Nullable<T>对象。有什么想法吗?

4 个答案:

答案 0 :(得分:8)

你想要typeof(Nullable<>).MakeGenericType(t)

注意:Nullable<> 没有任何提供的参数是未绑定的泛型类型;对于更复杂的示例,您可以添加逗号以适应 - 例如KeyValuePair<,>Tuple<,,,>等。

答案 1 :(得分:4)

你走在正确的轨道上。试试这个:

if (t.IsValueType)
{
    return typeof(Nullable<>).MakeGenericType(t);
}
else
{
    throw new ArgumentException();
}

答案 2 :(得分:1)

Type GetNullableType(Type type) {
    // Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper
    // if type is already nullable.
    type = Nullable.GetUnderlyingType(type);
    if (type.IsValueType)
        return typeof(Nullable<>).MakeGenericType(type);
    else
        return type;
} 

答案 3 :(得分:0)

最简单的解决方案是返回第一个GenericTypeArguments的UnderlyingSystemType。那么在这个例子中,Nullable Datetime?作为属性类型返回,我需要将其转换为Datetime类型,以便可以将其添加到DataTable。这应该适用于int?加倍?等

if (Nullable.GetUnderlyingType(prop.PropertyType) != null) {
  tb.Columns.Add(prop.Name, prop.PropertyType.GenericTypeArguments.First().UnderlyingSystemType);
} else {
  tb.Columns.Add(prop.Name, prop.PropertyType);
}