美文网首页
C# 两个类的映射

C# 两个类的映射

作者: 小耳朵_c199 | 来源:发表于2019-01-21 16:29 被阅读0次

使用对象映射的方式来赋值,实际上是利用了反射的机制,达到动态生成对象和动态类型转换的目的。
1.映射转换 从T1转换到T2 则根据T2的属性取T1对应属性值

        /// <summary>
        /// 映射转换 从T1转换到T2  则根据T2的属性取T1对应属性值
        /// </summary>
        /// <typeparam name="T1">转换前的对象</typeparam>
        /// <typeparam name="T2">转换后的对象</typeparam>
        /// <param name="fromModel">对象数据</param>
        /// <param name="action">回调函数 列如查出的是id  需要显示name情况</param>
        /// <returns></returns>
        public static T2 TransferData<T1, T2>(T1 fromModel,Action<T1,T2> action=null) where T2 : class
        {
            if (fromModel == null)
                return null;
            var t2 = IOC.CreateInstance<T2>();
            PropertyInfo[] propertys1 = IOC.GetProperties(typeof(T1));
            PropertyInfo[] propertys2 = IOC.GetProperties(typeof(T2));
            propertys2.ToList().ForEach(x => 
            {
                var p1 = propertys1.FirstOrDefault(o => o.Name == x.Name);
                if (p1 != null && x.CanWrite)
                {
                    try
                    {
                        var value = p1.GetValue(fromModel);
                        if (x.PropertyType == typeof(string))
                        {
                            x.SetValue(t2, value?.ToString());
                        }
                        else if (x.PropertyType == typeof(DateTime))
                        {
                            var datetime = Convert.ToDateTime(value);
                            x.SetValue(t2, datetime);
                        }
                        else if (x.PropertyType == typeof(int))
                        {
                            x.SetValue(t2, value.ChangeType(0));
                        }
                        else if (x.PropertyType == typeof(long))
                        {
                            x.SetValue(t2, value.ChangeType<long>(0));
                        }
                        else if (x.PropertyType == typeof(decimal))
                        {
                            x.SetValue(t2, value.ChangeType<decimal>(0));
                        }
                        else if (x.PropertyType == typeof(double))
                        {
                            x.SetValue(t2, value.ChangeType<double>(0));
                        }
                        else if (x.PropertyType == typeof(float))
                        {
                            x.SetValue(t2, value.ChangeType<float>(0));
                        }
                        else if(x.CanWrite)
                        {
                            x.SetValue(t2, value);
                        }
                    }
                    catch (Exception e)
                    {
            IO.Log.WriteLog(e.Message+ ",StackTrace:" + e.StackTrace);
                    }
                }
            });
            if (action != null)
            {
                action(fromModel,t2);
            }
            return t2;
        }

2.合并两个对象 从T1往T2合并 如果T2里面的数据是默认类型值 则从T1取数据往T2填充

        /// <summary>
        /// 合并两个对象 从T1往T2合并  如果T2里面的数据是默认类型值  则从T1取数据往T2填充
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="fromModel"></param>
        /// <param name="afterModel"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static T2 MergeData<T1, T2>(T1 fromModel,T2 afterModel, Action<T1, T2> action = null) where T2 : class
        {
            if (fromModel == null)
                return afterModel;
            if (afterModel == null)
                return null;
            //var t2 = IOC.CreateInstance<T2>();
            PropertyInfo[] propertys1 = IOC.GetProperties(typeof(T1));
            PropertyInfo[] propertys2 = IOC.GetProperties(typeof(T2));
            propertys2.ToList().ForEach(x =>
            {
                var p1 = propertys1.FirstOrDefault(o => o.Name == x.Name);
                var p2Value = x.GetValue(afterModel);
                if (p1 != null)
                {
                    try
                    {
                        var p1Value = p1.GetValue(fromModel);

                        if (x.PropertyType == typeof (string))
                        {
                            if (p1Value != null && p1Value.ToString() != "")
                                x.SetValue(afterModel, p1Value.ToString());
                        }
                        else if (x.PropertyType == typeof (DateTime))
                        {
                            //var datetime = Convert.ToDateTime(value);
                            //x.SetValue(t2, datetime);
                        }
                        else if (x.PropertyType == typeof (int))
                        {
                            if (Convert.ToInt32(p2Value) == 0 && Convert.ToInt32(p1Value) != 0)
                                x.SetValue(afterModel, p1Value);
                        }
                        else if (x.PropertyType == typeof (decimal))
                        {
                            if (Convert.ToDecimal(p2Value) == 0 && Convert.ToDecimal(p1Value) != 0)
                                x.SetValue(afterModel, p1Value);
                        }
                        else if (p2Value == null && p1Value != null)
                        {
                            x.SetValue(afterModel, p1Value);
                        }
                    }
                    catch
                    {
                        //ex.Error();
                    }
                }
            });
            if (action != null)
            {
                action(fromModel, afterModel);
            }
            return afterModel;
        }

3.转换一个集合类型数据

        /// <summary>
        /// 转换一个集合类型数据
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="list">数据源</param>
        /// <param name="action">回调函数 列如查出的是id  需要显示name情况</param>
        /// <returns></returns>
        public static List<T2> TransferData<T1, T2>(IEnumerable<T1> list,Action<T1, T2> action = null) where T2 : class
        {
            if (list == null)
                return null;
            var result = new List<T2>();
            foreach(var item in list)
            {
                var model = TransferData<T1, T2>(item,action);
                result.Add(model);
            }
            return result;
        }

相关文章

  • C# 两个类的映射

    使用对象映射的方式来赋值,实际上是利用了反射的机制,达到动态生成对象和动态类型转换的目的。1.映射转换 从T1转换...

  • 映射---> 一眼看懂Map

    映射:键值对 1.1 基本映射操作 Java类库提供两个基本的实现,HashMap和TreeMap。两个类都实现了...

  • 15. AutoMapper 之映射继承(Mapping Inh

    映射继承(Mapping Inheritance) 映射继承有两个功能: 从基类或接口配置继承映射配置 运行时多态...

  • 在ASP.NET Core中使用AutoMapper

    普通的模型映射 现在有两个类,实体类Student和返回展示的 View类StudentView 两个实体类字段还...

  • C#映射

    映射只是一种概念,它不像反射(是一种具体存在的技术),他只是将事物实现的某一种方法叫做映射。比如:在生活中(学校)...

  • Hibernate入门2-关联和映射

    Hibernate 快速入门2 - 关联映射和类继承 2 关联映射 我们知道两个表A、B的映射关系有 1-1, 1...

  • C#文件操作

    C#中文件操作主要可以使用StreamReader和StreamWriter两个类

  • 【原创】C#中的抽象类(abstract class)和接口(i

    在C#中抽象类和接口是两个相当重要的概念,深入理解对C#程序员是非常必要的,现总结如下: 一、抽象类的特点: 1、...

  • unity3d c#调用java

    c#调用java非静态方法 C#调用静态类,静态方法 ; CustomClass的静态类,SetData是它的静...

  • SpringData JPA第一章

    一、ORM思想 主要目的:操作实体类就相当于操作数据库表需要建立两个映射关系:①实体类和表的映射关系②实体类中属性...

网友评论

      本文标题:C# 两个类的映射

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