问题描述
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的。对于以上我可以简单地写诠释? NVAL = VAL
,但上面的代码动态执行。
I am getting InvalidCastException in above code. For above I could simply write int? nVal = val
, but above code is executing dynamically.
我收到(非可空类型喜欢整数,浮点等)值中的对象(这里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,文化=中立,
公钥= b77a5c561934e089]]'。
这是 INT
,应该是转换/类型强制转换为可空INT
,有什么问题吗?
An int
, should be convertible/type-castable to nullable int
, what is the issue here ?
推荐答案
您必须使用 Nullable.GetUnderlyingType
来得到基本类型可空$的C $ C>。
You have to use Nullable.GetUnderlyingType
to get underlying type of Nullable
.
这是可空我用它来克服
的changetype
限制的方式
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);
}
非泛型方法:
non generic method:
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程序]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!