Is it possible to convert a non-nullable value type known only at runtime to nullable? In other words:
public Type GetNullableType(Type t)
{
if (t.IsValueType)
{
return typeof(Nullable<t>);
}
else
{
throw new ArgumentException();
}
}
Obviously the return
line gives an error. Is there a way to do this? The Type.MakeGenericType
method seems promising, but I have no idea how to get a unspecified generic Type
object representing Nullable<T>
. Any ideas?
you want typeof(Nullable<>).MakeGenericType(t)
Note: Nullable<>
without any supplied arguments is the unbound generic type; for more complex examples, you would add commas to suit - ie KeyValuePair<,>
, Tuple<,,,>
etc.
You're on the right track. Try this:
if (t.IsValueType)
{
return typeof(Nullable<>).MakeGenericType(t);
}
else
{
throw new ArgumentException();
}
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;
}
The easiest solution is to return the UnderlyingSystemType of the first of the GenericTypeArguments. So in this example, a Nullable Datetime? is returning as the property type and I need to convert it to a Datetime type so it can be added to a DataTable. This should work with int? and double? etc.
if (Nullable.GetUnderlyingType(prop.PropertyType) != null) {
tb.Columns.Add(prop.Name, prop.PropertyType.GenericTypeArguments.First().UnderlyingSystemType);
} else {
tb.Columns.Add(prop.Name, prop.PropertyType);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.