关键词搜索

源码搜索 ×
×

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

发布2015-09-08浏览10868次

详情内容

原文地址:点击打开链接

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

  1. #region 将一个对象转换为指定类型
  2. /// <summary>
  3. /// 将一个对象转换为指定类型
  4. /// </summary>
  5. /// <param name="obj">待转换的对象</param>
  6. /// <param name="type">目标类型</param>
  7. /// <returns>转换后的对象</returns>
  8. public static object ConvertToObject(object obj, Type type)
  9. {
  10. if (type == null) return obj;
  11. if (obj == null) return type.IsValueType ? Activator.CreateInstance(type) : null;
  12. Type underlyingType = Nullable.GetUnderlyingType(type);
  13. if (type.IsAssignableFrom(obj.GetType())) // 如果待转换对象的类型与目标类型兼容,则无需转换
  14. {
  15. return obj;
  16. }
  17. else if ((underlyingType ?? type).IsEnum) // 如果待转换的对象的基类型为枚举
  18. {
  19. if (underlyingType != null && string.IsNullOrEmpty(obj.ToString())) // 如果目标类型为可空枚举,并且待转换对象为null 则直接返回null值
  20. {
  21. return null;
  22. }
  23. else
  24. {
  25. return Enum.Parse(underlyingType ?? type, obj.ToString());
  26. }
  27. }
  28. else if (typeof(IConvertible).IsAssignableFrom(underlyingType ?? type)) // 如果目标类型的基类型实现了IConvertible,则直接转换
  29. {
  30. try
  31. {
  32. return Convert.ChangeType(obj, underlyingType ?? type, null);
  33. }
  34. catch
  35. {
  36. return underlyingType == null ? Activator.CreateInstance(type) : null;
  37. }
  38. }
  39. else
  40. {
  41. TypeConverter converter = TypeDescriptor.GetConverter(type);
  42. if (converter.CanConvertFrom(obj.GetType()))
  43. {
  44. return converter.ConvertFrom(obj);
  45. }
  46. ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes);
  47. if (constructor != null)
  48. {
  49. object o = constructor.Invoke(null);
  50. PropertyInfo[] propertys = type.GetProperties();
  51. Type oldType = obj.GetType();
  52. foreach (PropertyInfo property in propertys)
  53. {
  54. PropertyInfo p = oldType.GetProperty(property.Name);
  55. if (property.CanWrite && p != null && p.CanRead)
  56. {
  57. property.SetValue(o, ConvertToObject(p.GetValue(obj, null), property.PropertyType), null);
  58. }
  59. }
  60. return o;
  61. }
  62. }
  63. return obj;
  64. }
  65. #endregion


相关技术文章

最新源码

下载排行榜

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载