C#通用类型转换 Convert.ChangeType
2024-08-30 13:25:30
//转换对象的成任何类型
//通用型
//效率不见得有多高
//当做特殊情况处理或者练习的话可以 public static object ChangeType(object value, Type type)
{
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);
else
return Enum.ToObject(type, value);
}
if (!type.IsInterface && type.IsGenericType)
{
Type innerType = type.GetGenericArguments()[];
object innerValue = ChangeType(value, innerType);
return Activator.CreateInstance(type, new object[] { innerValue });
}
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);
} //转载自 http://www.cnblogs.com/youring2/archive/2012/07/26/2610035.html
最新文章
- map 函数----filter函数
- C#之tcp自动更新程序
- oracle often commands
- quick-cocos2d-x之testlua之VisibleRect.lua
- [设计模式] Javascript 之 外观模式
- DEDECMS调用特定ID文章内容的实现方法
- 03-position和anchorPoint
- [.NET] 打造防“狼”神器 :任务栏篇
- 【html】【17】高级篇--loading加载
- my sql 实现批量操作及注意问题
- block代码块介绍
- iPhone图形开发绘图小结
- java提高篇(十一)-----代码块
- mysql基础篇-----mysql简介
- supermap数据库型数据源的数据索引问题
- POJ 3352 Road Construction ; POJ 3177 Redundant Paths (双联通)
- 1024. Video Stitching
- C#异步编程のWPF Invoke和BeginInvoke
- DSO windowed optimization 代码 (4)
- jar is specified twice.
热门文章
- linux下mysql基础从安装到基本使用
- 【HDU 4311】Meeting point-1(前缀和求曼哈顿距离和)
- C++强制类型转换操作符 const_cast
- python协程和yeild
- 【caffe】mnist训练日志
- 【BZOJ-4326】运输计划 树链剖分 + 树上差分 + 二分
- 【BZOJ-2503】相框 并查集 + 分类讨论
- PHPCMS \phpcms\modules\member\index.php 用户登陆SQL注入漏洞分析
- CentOS 7.0 安装配置LAMP服务器方法(Apache+PHP+MariaDB)
- iOS自动处理键盘事件的第三方库:IQKeyboardManager