2019-02-23 实体类转字典

// 设置Dictionary 得到实体类的字段名称和值

    public static Dictionary GetProperties(T t)
    {
        Dictionary ret = new Dictionary();

        if (t == null)
        {
            return null;
        }
        System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

        if (properties.Length <= 0)
        {
            return null;
        }
        foreach (System.Reflection.PropertyInfo item in properties)
        {
            string name = item.Name;                                                  //实体类字段名称
            string value = ObjToStr(item.GetValue(t, null));                //该字段的值
            
            if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
            {
                    ret.Add(name, value);        //在此可转换value的类型
            }
        }

        return ret;
    }

//反过来根据Dictionary来设置实体类

    public static T SetProperties(T t, Dictionary d)
    {
        if (t == null || d == null)
        {
            return default(T);
        }
        System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

        if (properties.Length <= 0)
        {
            return default(T);
        }
        foreach (System.Reflection.PropertyInfo item in properties)
        {
            string name = item.Name;                                         //名称
            string value = ObjToStr(item.GetValue(t, null));       //值

            if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
            {
                string val = d.Where(c => c.Key == name).FirstOrDefault().Value;
                if (val != null && val != value)
                {
                    if (item.PropertyType.Name.StartsWith("Nullable`1"))
                    {
                        item.SetValue(t, ObjToDate(val), null);
                    }
                    else
                    {
                        item.SetValue(t, val, null);
                    }
                }
            }
        }

        return t;
    }

你可能感兴趣的:(2019-02-23 实体类转字典)