C# 将一个对象转换为指定类型

原文地址:点击打开链接

适用:普通的对象,并且有默认的无参数构造函数

  #region 将一个对象转换为指定类型        ///         /// 将一个对象转换为指定类型        ///         /// 待转换的对象        /// 目标类型        /// 转换后的对象        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)!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1432253.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月17日 06:25:22
下一篇 2025年12月17日 06:25:33

相关推荐

发表回复

登录后才能评论
关注微信