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
查看全文
相关阅读:
SpringMVC注解控制器详解
在自己的服务器上安装GitBook
基于UDP协议的网络编程
RabbitMQ安装使用详解
Python3.4 + Django1.7.7 搭建简单的表单并提交
暴力枚举 UVA 10976 Fractions Again?!
暴力枚举 UVA 725 Division
思维 UVALive 3708 Graveyard
DFS(剪枝) POJ 1011 Sticks
DFS+模拟 ZOJ 3861 Valid Pattern Lock
原文地址:https://www.cnblogs.com/maplye/p/443391.html
最新文章
第十六章、Model/View开发:QColumnView的作用及对应Model
PyQt(Python+Qt)学习随笔:QColumnView的resizeGripsVisible属性
PyQt(Python+Qt)学习随笔:QTreeView树形视图的headerHiden属性
PyQt(Python+Qt)学习随笔:QTreeView树形视图的expandsOnDoubleClick属性
PyQt(Python+Qt)学习随笔:QTreeView的标题表头header相关属性
PyQt(Python+Qt)学习随笔:QTreeView树形视图的allColumnsShowFocus属性
装腔,你不能不学
ThinkPHP集锦
CentOS 6.4 中yum命令安装php5.2.17
centOS怎样强制卸载PHP以及自定义安装PHP
热门文章
利用securecrt在linux与windows之间传输文件
CentOS 6.2安装配置LAMP服务器(Apache+PHP5+MySQL)
vi命令使用
解决Linux下SSH等终端乱码问题
DedeTag Engine Create File False提示的种种原因及解决方法
IIS服务器访问网站出现403错误的解决方法
银联在线支付---利用测试案例代码模拟支付应用(修改)
银联在线支付----测试商户账号注册
python3.4 + Django1.7.7 表单的一些问题
Apache axis2 + Eclipse 开发 WebService
Copyright © 2011-2022 走看看