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
查看全文
相关阅读:
nginx配置url伪静态
PHP爬虫之queryList
PHP 判断给定两个时间是否在同一周,月,年
服务器nginx配置显示文件而不是下载
PHP yield占用内存测试
PHP 函数运行的内存
io系列之字节流
io系列之字符流
对于Arrays的deep相关的方法。
常用工具类(System,Runtime,Date,Calendar,Math)
原文地址:https://www.cnblogs.com/maplye/p/443391.html
最新文章
Linux内核7-中断和中断处理(上半部)
UNIX10-信号
Linux内核9、10-内核同步
数组_leetcode11
数组_leetcode26
数组_leetcode3
递归与二叉树_中序和后序重建二叉树
递归与二叉树_二叉树的基本操作
递归与二叉树_leetcode450
递归与二叉树_leetcode437
热门文章
递归与二叉树_leetcode404
递归与二叉树_leetcode257
递归与二叉树_leetcode236
爬虫
正则表达式
raise的使用
composer 发布一个自己的扩展包
PHP 根据域名和IP返回不同的内容
服务器nginx部署PHP项目样式不出来要注意的小问题
PHP 对参数签名
Copyright © 2011-2022 走看看