博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据类型转换
阅读量:4446 次
发布时间:2019-06-07

本文共 1450 字,大约阅读时间需要 4 分钟。

/// <summary>

/// 数据类型转换
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="value">源数据</param>
/// <param name="defaultValue">默认值</param>
/// <returns>结果</returns>
public static T To<T>(object value, T defaultValue)
{
/* T obj;
try {
if (value == null) {
return defaultValue;
}
obj = (T)Convert.ChangeType(value, typeof(T));
if (obj == null) {
obj = defaultValue;
}
} catch {
obj = defaultValue;
}
return obj;*/
T obj = default(T);
try
{
if (value == null)
{
return defaultValue;
}
var valueType = value.GetType();
var targetType = typeof(T);
tag1:
if (valueType == targetType)
{
return (T)value;
}
if (targetType.IsEnum)
{
if (value is string)
{
return (T)System.Enum.Parse(targetType, value as string);
}
else
{
return (T)System.Enum.ToObject(targetType, value);
}
}
if (targetType == typeof(Guid) && value is string)
{
object obj1 = new Guid(value as string);
return (T)obj1;

}

if (targetType == typeof(DateTime) && value is string)
{
DateTime d1;
if (DateTime.TryParse(value as string, out d1))
{
object obj1 = d1;
return (T)obj1;
}

}
if (targetType.IsGenericType)
{
if (targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
targetType = Nullable.GetUnderlyingType(targetType);
goto tag1;
}
}
if (value is IConvertible)
{
obj = (T)Convert.ChangeType(value, typeof(T));
}

if (obj == null)

{
obj = defaultValue;
}
}
catch
{
obj = defaultValue;
}
return obj;
}

转载于:https://www.cnblogs.com/guzhengtao/p/20180706_1553.html

你可能感兴趣的文章
php 解决乱码的通用方法
查看>>
spring aop annotation
查看>>
RSA加密解密及RSA签名和验证
查看>>
解题报告:hdu1257 LIS裸题
查看>>
P2939 [USACO09FEB]改造路Revamping Trails
查看>>
Add some compression to your program
查看>>
动态识别类型
查看>>
JBOSSAS 5.x/6.x 反序列化命令执行漏洞(CVE-2017-12149)
查看>>
Error: Could not find or load main class test.EditFile
查看>>
cocos2d-2.0-rc0a-x-2.0避免copy文件夹和库方法
查看>>
python提取隐含结构的字符串
查看>>
conversation with super KDL
查看>>
3. Git与TortoiseGit基本操作
查看>>
正則表達式匹配号码
查看>>
Codeforces Beta Round #10 B. Cinema Cashier (树状数组)
查看>>
Zookeeper zkui-zookeeper图形化管理工具
查看>>
线段树
查看>>
LLVM提议向C语言中加入模块机制
查看>>
免费学习视频
查看>>
Winodws10 &system进程占用磁盘100%
查看>>