C# 将一个对象转换为指定类型
2023-09-14 09:02:13 时间
原文地址:点击打开链接
适用:普通的对象,并且有默认的无参数构造函数
#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,则直接转换 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# 将Excel转换为PDF
- C#.NET常见问题(FAQ)-浮点数如何四舍五入
- C#基础视频教程6.1 如何简单读写数据库
- c# 后端与前端时间戳的转换
- RSA密钥之C#格式与Java格式转换
- 重学c#系列——c#运行原理(二)
- C# where泛型约束
- C# ExecuteNonQuery()的返回值
- C# 将字符串(符合xml格式)转换为XmlDocument
- Atitit.跨语言异常转换机制 java c# php到js的异常转换
- Atitit.跨语言异常转换机制 java c# php到js的异常转换
- Atitit.jsou html转换纯文本 java c# php
- (五十八)c#Winform自定义控件-管道阀门(工业)-HZHControls
- (十)c#Winform自定义控件-横向列表-HZHControls
- C#使用xpath找到一个节点
- (14)C#的网络接收和发送的各种大小端字节转换
- 在C#主线程和子线程将数据传递给对方如何实现
- C#开发PACS医学影像处理系统(十九):Dicom影像放大镜
- Visual Studio 2019 使用C语言创建动态链接库(Dll)并使用C语言和C#实现调用
- C#创建Windows窗体应用程序实例3【个人信息调查】