通过反射获取对象名称和值

 

 

 1 void Main()
 2 {
 3     var s1=new Student();
 4     s1.name="xiao";
 5     s1.age=22;
 6     var str = MapProperty(s1);
 7     
 8     List<Student> list = new List<Student>();
 9     list.Add(s1);
10     
11     Console.WriteLine(str);
12 }
13 
14 class Student
15 {
16     public string name{get;set;}
17     public int age{get;set;}
18 }
19 
20 string MapProperty<T>(T t)
21 {
22     var name=new StringBuilder();
23     var value = new StringBuilder();
24     PropertyInfo[] propertyInfos = t.GetType().GetProperties();
25     
26     if(propertyInfos.Length>0)
27     {
28         foreach(var info in propertyInfos)
29         {
30             name.Append(info.Name);
31             name.Append(" = ");
32             name.Append(info.GetValue(t)+"\n");
33         }
34     }
35     return name.ToString();
36 }

 

结果

name = xiao
age = 22

 

posted @ 2019-05-08 21:48  mantishell  阅读(1124)  评论(0编辑  收藏  举报