using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SamplePre.Common { public class ReflectionCommHelper { /// /// 根据属性名获取对象的属性值(支持公共/非公共属性) /// /// 目标对象(不能为null) /// 属性名(大小写敏感) /// 是否忽略大小写(默认false) /// 属性值(不存在返回null) public static object GetPropertyValue(object obj, string propertyName, bool ignoreCase = false) { // 空值校验 if (obj == null) throw new ArgumentNullException(nameof(obj), "目标对象不能为null"); if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException(nameof(propertyName), "属性名不能为空"); // 获取对象类型 Type type = obj.GetType(); // 获取属性信息(BindingFlags控制是否查找非公共/实例成员) PropertyInfo propInfo = type.GetProperty( propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | (ignoreCase ? BindingFlags.IgnoreCase : BindingFlags.Default) ); // 属性不存在返回null if (propInfo == null) return null; // 获取属性值 return propInfo.GetValue(obj); } } }