zoukankan      html  css  js  c++  java
  • C# 对象互转

            /// <summary>
            /// 适用于初始化新实体
            /// </summary>
            static public T RotationMapping<T, S>(S s)
            {
                T target = Activator.CreateInstance<T>();
                var originalObj = s.GetType();
                var targetObj = typeof(T);
                foreach (PropertyInfo original in originalObj.GetProperties())
                {
                    foreach (PropertyInfo t in targetObj.GetProperties())
                    {
                        if (t.Name == original.Name)
                        {
                            t.SetValue(target, original.GetValue(s, null), null);
                        }
                    }
                }
                return target;
            }
            /// <summary>
            /// 适用于没有新建实体之间
            /// </summary>
            static public T RotationMapping<T, S>(T t, S s)
            {
                var originalObj = s.GetType();
                var targetObj = typeof(T);
                foreach (PropertyInfo sp in originalObj.GetProperties())
                {
                    foreach (PropertyInfo dp in targetObj.GetProperties())
                    {
                        if (dp.Name == sp.Name)
                        {
                            dp.SetValue(t, sp.GetValue(s, null), null);
                        }
                    }
                }
                return t;
            }
            static public void AutoMapping<S, T>(S s, T t)
            {
                PropertyInfo[] pps = GetPropertyInfos(s.GetType());
                Type target = t.GetType();
    
                foreach (var pp in pps)
                {
                    PropertyInfo targetPP = target.GetProperty(pp.Name);
                    object value = pp.GetValue(s, null);
    
                    if (targetPP != null && value != null)
                    {
                        targetPP.SetValue(t, value, null);
                    }
                }
    
            }
    
            static public PropertyInfo[] GetPropertyInfos(Type type)
            {
                return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
  • 相关阅读:
    NOIP 2012 T5 借教室 [洛谷P1083]
    POJ2437 Muddy roads
    POJ2288 Islands and Bridges
    洛谷P2014 TYVJ1051 选课
    POJ1741 Tree
    CODEVS1995 || TYVJ1863 黑魔法师之门
    TYVJ1939 玉蟾宫
    TYVJ1305 最大子序和
    POJ1737 Connected Graph
    TYVJ1864 守卫者的挑战
  • 原文地址:https://www.cnblogs.com/hofmann/p/11756933.html
Copyright © 2011-2022 走看看