zoukankan
html css js c++ java
Nullable 类型的转换
今天碰到Nullable 不能通过Convert.ChangeType转换,辛苦在网上找到两个解决方法,共享一下。
1.
The PumaCode.org Blog
public
object
ChangeType(
object
value, Type conversionType)
{
if
( conversionType.IsGenericType
&&
conversionType.GetGenericTypeDefinition( ).Equals(
typeof
( Nullable
<>
) ) )
{
if
(value
==
null
)
return
null
;
System.ComponentModel.NullableConverter nullableConverter
=
new
System.ComponentModel.NullableConverter(conversionType);
conversionType
=
nullableConverter.UnderlyingType;
}
return
Convert.ChangeType(value, conversionType);
}
引用:
http://blog.pumacode.org/2006/05/18/using-convert-changetype-on-nullable-types/
2.
Paul Wilson's .NET Blog
public
class
DataTypeConverter
{
public
static
object
ChangeType(Type type,
object
value)
{
if
((value
==
null
)
&&
type.IsGenericType)
{
return
Activator.CreateInstance(type);
}
if
(value
==
null
)
{
return
null
;
}
if
(type
==
value.GetType())
{
return
value;
}
if
(type.IsEnum)
{
if
(value
is
string
)
{
return
Enum.Parse(type, value
as
string
);
}
return
Enum.ToObject(type, value);
}
if
(
!
type.IsInterface
&&
type.IsGenericType)
{
Type type1
=
type.GetGenericArguments()[
0
];
object
obj1
=
DataTypeConverter.ChangeType(type1,value);
return
Activator.CreateInstance(type,
new
object
[]
{ obj1 }
);
}
if
((value
is
string
)
&&
(type
==
typeof
(Guid)))
{
return
new
Guid(value
as
string
);
}
if
((value
is
string
)
&&
(type
==
typeof
(Version)))
{
return
new
Version(value
as
string
);
}
if
(
!
(value
is
IConvertible))
{
return
value;
}
return
Convert.ChangeType(value, type);
}
}
这个代码是WilsonORMapper中的QueryHelper类,不好意思,我Reflector了一下。
引用:
http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx
查看全文
相关阅读:
一个强悍的强制删除文件的批处理
禁止用户使用QQ聊天工具
《项目经理指导手册》附录2项目经理面试题
《项目经理指导手册》 附录1每日站会评价表
《项目经理指导手册》调研篇
《项目经理指导手册》前言
《项目经理指导手册》 会议篇
从Log4j2今天的漏洞说起.
Asp.Net将Excel数据导入Sql Server数据库的的例子
Winform窗体程序输入法全角问题
原文地址:https://www.cnblogs.com/maplye/p/443391.html
最新文章
GO程序运行久了以后宕机问题如何定位
golang查看panic详细对战信息
GO test的用法
Golang限制请求频率 + 接受超时信号后停止发送请求
一步一步学习sharepoint2010 系列篇
一步一步学习sharepoint2010 workflow 系列第三部分:自定义SharePoint代码工作流 第12章 工作流开发技巧包 (A bag of workflow developer tricks)
一步一步学习sharepoint2010 workflow 系列第三部分:自定义SharePoint代码工作流 第11章 自定义工作流活动和条件(Custom workflow activities and conditions)
一步一步学习sharepoint2010 workflow 系列第三部分:自定义SharePoint代码工作流 第8章 自定义Visual Studio工作流(Custom Visual Studio workflows)
一步一步学习sharepoint2010 workflow 系列第三部分:自定义SharePoint代码工作流 第10章 工作流和任务处理(Workflows and task processes)
一步一步学习sharepoint2010 workflow 系列第三部分:自定义SharePoint代码工作流 第9章 Visual Studio工作流表单(Forms in Visual Studio workflows)
热门文章
使用VBS实现批量修改
Intent Actions
附加数据库失败,无法升级数据库,因为它是只读的
mysql 从中英文混合串中截取字符
RelativeLayout
Android 记事本开发实例详解
C# 两个datatable中的数据快速比较返回交集或差集
android中的UriMatcher和ContentUris
U盘flash引脚短路修复
使虚拟系统随系统的启动而启动
Copyright © 2011-2022 走看看