问题描述
Type t = typeof(int?); //will get this dynamically
object val = 5; //will get this dynamically
object nVal = Convert.ChangeType(val, t);//getting exception here
我在上面的代码中收到 InvalidCastException.对于上面我可以简单地写 int?nVal = val
,但上面的代码是动态执行的.
I am getting InvalidCastException in above code. For above I could simply write int? nVal = val
, but above code is executing dynamically.
我得到一个值(非空类型,如 int、float 等)包裹在一个对象(这里是 val)中,我必须通过将它转换为另一种类型(可以或不能)来将它保存到另一个对象是它的可为空版本).当
I am getting a value(of non nullable type like int, float, etc) wrapped up in an object (here val), and I have to save it to another object by casting it to another type(which can or cannot be nullable version of it). When
从 'System.Int32' 到 'System.Nullable`1[[System.Int32,mscorlib,版本=4.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089]]'.
一个 int
,应该可以转换/类型转换为 nullable int
,这里有什么问题?
An int
, should be convertible/type-castable to nullable int
, what is the issue here ?
推荐答案
您必须使用 Nullable.GetUnderlyingType
来获取 Nullable
的底层类型.
You have to use Nullable.GetUnderlyingType
to get underlying type of Nullable
.
这是我用来克服 ChangeType
对于 Nullable
This is the method I use to overcome limitation of ChangeType
for Nullable
public static T ChangeType<T>(object value)
{
var t = typeof(T);
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default(T);
}
t = Nullable.GetUnderlyingType(t);
}
return (T)Convert.ChangeType(value, t);
}
非泛型方法:
public static object ChangeType(object value, Type conversion)
{
var t = conversion;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
t = Nullable.GetUnderlyingType(t);
}
return Convert.ChangeType(value, t);
}
这篇关于从“System.Int32"到“System.Nullable"1[[System.Int32, mscorlib]] 的无效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!