public static object ChangeType(object value, Type targetType)
{ if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof (Nullable<>))
{
NullableConverter nullableConverter = new NullableConverter(targetType);
Type convertType = nullableConverter.UnderlyingType;
return Convert.ChangeType(value, convertType);
}
if (value == null && targetType.IsGenericType)
{
return Activator.CreateInstance(targetType);
}
if (value == null)
{
return null;
}
if (targetType == value.GetType())
{
return value;
}
if (targetType.IsEnum)
{
if (value is string)
{
return Enum.Parse(targetType, value as string);
}
else
{
return Enum.ToObject(targetType, value);
}
}
if (!targetType.IsInterface && targetType.IsGenericType)
{
Type innerType = targetType.GetGenericArguments()[];
object innerValue = ChangeType(value, innerType);
return Activator.CreateInstance(targetType, new object[] { innerValue });
}
if (value is string && targetType == typeof (Guid))
{
return new Guid(value as string);
}
if (value is string && targetType == typeof (Version))
{
return new Version(value as string);
}
if (!(value is IConvertible))
{
return value;
}
return Convert.ChangeType(value, targetType);
}

最新文章

  1. Git 冲突合并
  2. [Data Structure] 数据结构中各种树
  3. WCF学习总结
  4. 微信小程序 wx.uploadFile在安卓手机上面the same task is working问题解决
  5. GoLang之方法与接口
  6. CSS:z-index层级在IE中无效
  7. ftrace的使用【转】
  8. MySQL(15):Select-distinct(返回非重复的记录)
  9. JavaMail回复
  10. BZOJ 1103 [POI2007]大都市meg(树状数组+dfs序)
  11. C#截取用户的点击事件的代码
  12. 配置babel
  13. PL/SQL如何调试sql语句、存储过程
  14. fiddler 笔记-重定向
  15. Vuex的API文档
  16. Oracle简单的序列应用
  17. poj 2406 求字符串中重复子串的个数
  18. JdbcTemplate中向in语句传参
  19. 4、申请开发(Development)证书和描述文件
  20. hashlib 简单的登录例子

热门文章

  1. JavaScript 随笔1
  2. I/O流——字节流
  3. man curl_easy_init(原创)
  4. 检查项目里是否有IDFA的方法
  5. 利用GCTA工具计算复杂性状/特征(Complex Trait)的遗传相关性(genetic correlation)
  6. TOMCAT的安装部署配置(配图解)
  7. (转)如何在一台电脑上开启多个tomcat 和配置让系统识别哪个具体的tomcat
  8. c# DESEncrypt 加密、解密算法
  9. 2、C语言关键字-auto register static
  10. MongoDB 知识要点一览