C# 反射获取和设置值

 

 1     /// <summary>
 2         /// 遍历泛型
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="obj"></param>
 6         /// <returns></returns>
 7         public static List<T> Abcdefg<T>(List<T> obj)
 8         {
 9             foreach (T t in obj)
10             {
11                 if (t == null)
12                 {
13                     continue;
14                 }
15                 PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
16                 int length = myPropertyInfo.Length;
17                 for (int i = 0; i < length; i++)
18                 {
19                     PropertyInfo pi = myPropertyInfo[i];
20                     // 获取值
21                     pi.GetValue(t, null);
22                     // 修改值
23                     pi.SetValue(t, "要修改的值,但是必须保证与当前字段类型相同", null);
24 
25                 }
26             }
27             return obj;
28         }
View Code

 

posted @ 2015-12-30 16:13  gaozejie  阅读(1456)  评论(0编辑  收藏  举报