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 }
本文来自博客园,作者:yun5,转载请注明原文链接:https://www.cnblogs.com/yun5/articles/16699085.html

浙公网安备 33010602011771号