c# 反射的方式 获取.设置实例字段


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

        public static Dictionary<string, string> GetProperties<T>(T t)

        {

            Dictionary<string, string> ret = new Dictionary<string, string>();

 

            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 t, Dictionary<string, string> 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;

        }
//https://blog.csdn.net/github_37830343/article/details/79030333

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值