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
查看全文
相关阅读:
怎么对Navicat for Oracle 调试
老版本的java代码与新代码如何找出差异
Oracle 外部表是做什么用的
如何在Navicat 中编辑和记录
如何使用文件对比工具文件夹比较会话菜单
哪些工具可以用来进行Bug管理
5类开发者须知的工具
怎么找出代码之间的差异
Beyond Compare不仅可以修改网页代码
文件对比工具有哪些用途
原文地址:https://www.cnblogs.com/maplye/p/443391.html
最新文章
hdu 2157 How many ways?? 矩阵快速幂
hdu 1757 A Simple Math Problem 矩阵优化+快速幂
hdu 5360 Hiking
hdu 1575 try a 矩阵快速幂
hdu 5363 Key Set 矩阵快速幂
POJ Ultra-2299 QuickSort 【离散化+树状数组】
Codeforces 29C Mail Stamps【离散化+DFS】
POJ 3320 Jessica's Reading Problem 【尺取法】
POJ 3061 Subsequence 【尺取法】
HDU Problem 1166 敌兵布阵 【树状数组 & 线段树】
热门文章
Codeforces 706B Interesting drink 【二分】
HDU Problem 1179 Ollivanders: Makers of Fine Wands since 382 BC.【二分图匹配】
ZZULIOJ 1919: D【二分】
ZZULIOJ 1918: G 【二分图匹配】
HDU Problem 5395 Gym Class 【拓扑排序+优先队列】
HDU Problem 2955 Robberies 【01背包】
HDU Problem 3466 Proud Merchants【01背包】
HDU Problem 1203 I NEED A OFFER! 【01背包】
POJ Problem 3624 Charm Bracelet 【01背包】
HDU Problem 2546 饭卡【01背包】
Copyright © 2011-2022 走看看