Files
SamplePreSystem-CS/SamplePre.Common/Helper/ReflectionCommHelper.cs
2026-04-30 11:34:41 +08:00

47 lines
1.6 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}
}