C#通过反射实现设置属性值和获取属性值

 1        // 获取类中的属性值
 3         public string GetModelValue(string FieldName, object obj){
 4             try
 5             {
 6                 Type t = obj.GetType();
 7                 object o = t.GetProperty(FieldName).GetValue(obj, null);
 8                 string Value = Convert.ToString(o);
 9                 if (string.IsNullOrEmpty(Value)) return null;
10                 return Value;
11             }
12             catch
13             {
14                 return null;
15             }
16         }
17 
18        
19         // 设置类中的属性值
21         public bool SetModelValue(string FieldName,string Value, object obj){
22             try{
23                 Type t = obj.GetType();
24                 object v = Convert.ChangeType(Value, t.GetProperty(FieldName).PropertyType);
25                 t.GetProperty(FieldName).SetValue(obj, v, null);
26                 return true;
27             }
28             catch{
29                 return false;
30             }
31         }

 

posted @ 2022-09-16 10:52  yun5  阅读(142)  评论(0)    收藏  举报
Title