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

jjo*_*son 3 c# reflection nullable

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

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

显然这return条线会出错.有没有办法做到这一点?该Type.MakeGenericType方法似乎很有希望,但我不知道如何获得一个未指定的通用Type对象表示Nullable<T>.有任何想法吗?

Mar*_*ell 8

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

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

  • @jjoelson - 注意你也应该检查底层类型,因为你不允许创建`Nullable <Nullable <int >>`等等 - 考虑:如果`t == typeof(float?)`(它有`.ValueType怎么办? === true`) (2认同)

Ada*_*son 5

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

if (t.IsValueType)
{
    return typeof(Nullable<>).MakeGenericType(t);
}
else
{
    throw new ArgumentException();
}
Run Code Online (Sandbox Code Playgroud)