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
查看全文
相关阅读:
火柴排队sol
国王游戏sol
子串sol
跳石头
解方程sol
花匠sol
字符串整理
计算系数
矩阵取数游戏sol
8.2_java_28
原文地址:https://www.cnblogs.com/maplye/p/443391.html
最新文章
Java 接口
Java 克隆
VS Code小白使用教程
VS Code 上那些沙雕插件
我在 GitHub 上发现了一款骚气满满的字体!
Linux 终端最全推荐(建议收藏)
大家用了之后都在推荐的 42 款插件,我整理出来了
17 个 Python 特别实用的操作技巧,记得收藏!
c++ 重写(override)与重定义(redifine)
c++ tuple
热门文章
「暑期集训day19」浮光
[暑期集训]Day18 呐喊
暑假日报-23
暑假日报-22
Redis 搭建与配置
MySQL 优化
34 | 站在巨人的肩膀:企业级实际性能测试案例与经验分享
33 | 无实例无真相:基于LoadRunner实现企业级服务器端性能测试的实践(下)
32 | 无实例无真相:基于LoadRunner实现企业级服务器端性能测试的实践(上)
运输计划sol
Copyright © 2011-2022 走看看