Invalid cast from #39;System.Int32#39; to #39;System.Nullable`1[[System.Int32, mscorlib]](从 System.Int32 到 System.Nullable`1[[System.Int32, mscorlib]] 的无效转换)
问题描述
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]]'.
Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, 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.
这是我用来克服 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);
}
非泛型方法:
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]] 的无效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 'System.Int32' 到 'System.Nullable`1[[System.Int32, mscorlib]] 的无效转换
基础教程推荐
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
