C# 将一个对象转换为指定类型
原文地址:点击打开链接
适用:普通的对象,并且有默认的无参数构造函数
#region 将一个对象转换为指定类型 /// <summary> /// 将一个对象转换为指定类型 /// </summary> /// <param name="obj">待转换的对象</param> /// <param name="type">目标类型</param> /// <returns>转换后的对象</returns> public static object ConvertToObject(object obj, Type type) { if (type == null) return obj; if (obj == null) return type.IsValueType ? Activator.CreateInstance(type) : null; Type underlyingType = Nullable.GetUnderlyingType(type); if (type.IsAssignableFrom(obj.GetType())) // 如果待转换对象的类型与目标类型兼容,则无需转换 { return obj; } else if ((underlyingType ?? type).IsEnum) // 如果待转换的对象的基类型为枚举 { if (underlyingType != null && string.IsNullOrEmpty(obj.ToString())) // 如果目标类型为可空枚举,并且待转换对象为null 则直接返回null值 { return null; } else { return Enum.Parse(underlyingType ?? type, obj.ToString()); } } else if (typeof(IConvertible).IsAssignableFrom(underlyingType ?? type)) // 如果目标类型的基类型实现了IConvertible,则直接转换 { try { return Convert.ChangeType(obj, underlyingType ?? type, null); } catch { return underlyingType == null ? Activator.CreateInstance(type) : null; } } else { TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter.CanConvertFrom(obj.GetType())) { return converter.ConvertFrom(obj); } ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor != null) { object o = constructor.Invoke(null); PropertyInfo[] propertys = type.GetProperties(); Type oldType = obj.GetType(); foreach (PropertyInfo property in propertys) { PropertyInfo p = oldType.GetProperty(property.Name); if (property.CanWrite && p != null && p.CanRead) { property.SetValue(o, ConvertToObject(p.GetValue(obj, null), property.PropertyType), null); } } return o; } } return obj; } #endregion
登录后复制
以上就是C# 将一个对象转换为指定类型的内容,更多相关内容请关注PHP中文网(www.php.cn)!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
刺客信条阴影:贝壳谜语解决方案
2 周前
By DDD
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前
By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前
By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

使用 C# 的 Active Directory 指南。在这里,我们讨论 Active Directory 在 C# 中的介绍和工作原理以及语法和示例。
