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
查看全文
相关阅读:
MySQL-3(练习题)-三套知识点看完SQL没问题
MySQL知识点-2(超详细)
MySQL知识点-1(超详细)
MySQL表结构笔记9
MySQL增删改查&数据类型笔记8
07:表联结MySQL笔记7
spring事务传播机制
MySQL查看两个查询的差集
python连接数据库
chrome一款可以在浏览器编辑hosts文件的插件HostAdmin App
原文地址:https://www.cnblogs.com/maplye/p/443391.html
最新文章
P3792 由乃与大母神原型和偶像崇拜
P1412 经营与开发
架设电话线 二分+图论
山山赚钱记 二分+图论
危险的迷宫 网络流
树链剖分
魔兽 DP
[ural 2120]. Tree Average Weight
[ural 2119]. Tree Hull
[ural 2121]. Intersection of Parabolas
热门文章
[ural 2125]. Continue the Sequence && [loj 166]. 拉格朗日插值 2
[ural 2123]. Knapsack
[ural 2126]. Partition into Teams
[ural 2124]. Algebra on Segment
loj rounds 补题
两种判圈法——floyd和brent
python习题-3
python习题-2
python习题-1
03:列表与元组
Copyright © 2011-2022 走看看