47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
|
|
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
|
|||
|
|
{
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 根据属性名获取对象的属性值(支持公共/非公共属性)
|
|||
|
|
/// </summary>
|
|||
|
|
/// <param name="obj">目标对象(不能为null)</param>
|
|||
|
|
/// <param name="propertyName">属性名(大小写敏感)</param>
|
|||
|
|
/// <param name="ignoreCase">是否忽略大小写(默认false)</param>
|
|||
|
|
/// <returns>属性值(不存在返回null)</returns>
|
|||
|
|
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);
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
}
|