美文网首页
C#把object转换为指定Type类型

C#把object转换为指定Type类型

作者: 堆石成山 | 来源:发表于2023-11-05 15:30 被阅读0次

传递过来的数据是obj,知道他的类型Type,那么转换如下:

      /// <summary>
        /// 把object转换为指定Type类型
        /// </summary>
        /// <param name="obj">需要转换的对象</param>
        /// <param name="type">指定转换的类型</param>
        /// <returns>返回object</returns>
        private 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()))
                {
                    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 (Exception)
                {
                    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 item in propertys)
                    {
                        PropertyInfo p = oldType.GetProperty(item.Name);
                        if(item.CanWrite&&p!=null&&p.CanRead)
                        {
                            item.SetValue(o,ConvertToObject(p.GetValue(obj,null),item.PropertyType),null);
                        }
                    }
                    return o;
                }
            }

            return obj;
        }

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

相关文章

  • Python isinstance() 判断指定对象数据类型

    isinstance(object, type)如果指定的对象拥有指定的类型,则 isinstance() 函数返...

  • 装箱和拆箱

    装箱就是把值类型转换为引用类型 拆箱就是把引用类型转换为值类型 封箱:把值类型转换为System.Object类型...

  • Unity常见面试题(一)

    1. [C#语言基础]请简述拆箱和装箱。 答: 装箱操作: 值类型隐式转换为object类型或由此值类型实现的任何...

  • 第一天:C# 值类型、引用类型、装箱与拆箱

    C#中类型分为两类: 值类型(Value Type) 引用类型(Reference Type) 值类型和引用类型是...

  • C#数据类型转换

    类型转换从根本上说是类型铸造,或者说是把数据从一种类型转换为另一种类型。在 C# 中,类型铸造有两种形式: 隐式转...

  • 类型判断type与isinstance的区别

    类型判断type与isinstance的区别 type()函数:语法type(object)type(name, ...

  • q第三章 类型、值和变量

    数据类型: 原始类型(primitive type)和对象类型(object type)。原始类型包括: 对象是属...

  • dart 基础语法

    var j;//Object类型,如果指定了值 就是具体类型,没有指定就是Object类型j = 10;j = “...

  • List>转换为泛型Li

    List >转List 传入需要转换的clazz Map的值Object转换为T的Field对应类型

  • c# 学习笔记2

    C# 类型转换类型转换从根本上说是类型铸造,或者说是把数据从一种类型转换为另一种类型。在 C# 中,类型铸造有两种...

网友评论

      本文标题:C#把object转换为指定Type类型

      本文链接:https://www.haomeiwen.com/subject/cngzidtx.html