代码包含两个方法:GetPropertyValue
和 SetPropertyValue
。这两个方法都是泛型方法,可以用于获取和设置对象的属性值。
在 GetPropertyValue
方法中:
- 首先获取传入对象的类型。
- 查找指定属性名称的属性,并忽略大小写。
- 如果找不到属性,则返回空字符串。
- 获取该属性的值,并将其转换为字符串返回。
在 SetPropertyValue
方法中:
- 获取传入对象的类型。
- 使用指定属性名称获取属性。
- 如果找不到属性,则返回空字符串。
- 使用
SetValue
方法设置属性的值为传入的字段值。public string GetPropertyValue<T>(T model, string fieldName) { Type type = typeof(T);//或者 Type type = model.GetType(); PropertyInfo property = type.GetProperties() .FirstOrDefault(p => string.Equals(p.Name, fieldName, StringComparison.OrdinalIgnoreCase)); //PropertyInfo property = type.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (property == null) return string.Empty; object fieldValue = property.GetValue(model, null); if (fieldValue == null) return string.Empty; return fieldValue.ToString(); } public T SetPropertyValue<T>(T model, string fieldName, object fieldValue) { model.GetType().GetProperty(fieldName).SetValue(model, fieldValue); Type type = typeof(T);//或者 Type type = model.GetType(); PropertyInfo property = type.GetProperties() .FirstOrDefault(p => string.Equals(p.Name, fieldName, StringComparison.OrdinalIgnoreCase)); //PropertyInfo property = type.GetProperty(field, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if (property == null) return string.Empty; object fieldValue = property.SetValue(model, fieldValue); if (fieldValue == null) return string.Empty; return fieldValue.ToString(); }