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