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>.有任何想法吗?
你要 typeof(Nullable<>).MakeGenericType(t)
注意:Nullable<> 没有任何提供的参数是未绑定的泛型类型; 对于更复杂的例子中,可以添加逗号,以适应-即KeyValuePair<,>,Tuple<,,,>等等.
你在正确的轨道上。尝试这个:
if (t.IsValueType)
{
return typeof(Nullable<>).MakeGenericType(t);
}
else
{
throw new ArgumentException();
}
Run Code Online (Sandbox Code Playgroud)