数据转换

实体对象数据转结构体

                //原始对象
                Test test = new Test();
                test.Name = "反射";
                var props = test.GetType().GetProperties();
                StructData structData = new StructData();
                Object someBoxedStruct = structData;
                StructData someUnBoxedStruct = new StructData();
                foreach (var item in props)
                {
                    var setobj = structData.GetType().GetProperty(item.Name);
                    //从旧对象中获取值
                    var value = item.GetValue(test, null);
                    Type myType = typeof(StructData);
                    FieldInfo myFieldInfo = myType.GetField(item.Name);
                    myFieldInfo.SetValue(someBoxedStruct, value.ToString());
                    someUnBoxedStruct = (StructData)someBoxedStruct;
                }

  

实体对象A转实体对象B

            //原始数据
            Test test = new Test();
            var tests = test.GetType().GetProperties();
            //赋值对象
            Test1 test1 = new Test1();
            foreach (var inst in tests)
            {
                var test1Name = test1.GetType().GetProperty(inst.Name);
                if (test1Name==null)
                {
                    continue;
                }
                //获取数据
                var value = inst.GetValue(test, null);
                test1Name.SetValue(test1, value);
            }

  

posted @ 2020-07-02 23:12  *飞*  阅读(119)  评论(0编辑  收藏  举报