反射的属性获取与设置

using System;
using System.Linq;
using System.Reflection;

namespace ClassReflector.Common
{
public class TProperty<T>
{
/// <summary>
/// Get All Properties of specified Type
/// </summary>
/// <returns></returns>
public static PropertyInfo[] GetPropertyInfoArray(Type type, bool isCheckCustomAttributes = false)
{
PropertyInfo[] props = null;
try
{
var obj = Activator.CreateInstance(type);
if (isCheckCustomAttributes)
{
props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToArray();
}
else
{
props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).
OrderBy(T => T.CustomAttributes.Count() > 0
? ((OrderAttribute) (T.GetCustomAttributes().
Where(A => "OrderAttribute".Equals(A.GetType().Name)).First())).Order
: 0).Where(A => ((VisibleAttribute) (A.GetCustomAttributes().
Where(B => "VisibleAttribute".Equals(B.GetType().Name)).First())).Visible).ToArray();
}
}
catch (Exception ex)
{
throw;
}
return props;
}

public static object GetValueByPropertyName(Type type, T obj, object propName)
{
object propertyValue = null;
var propInfos = GetPropertyInfoArray(type);
foreach (var pi in propInfos)
{
if (pi.Name.Equals(propName))
{
propertyValue = pi.GetValue(obj, null);
break;
}
}
return propertyValue;
}

public static bool SetModifyByPropertyName(Type type, T obj, object propName, object propValue)
{
var propInfos = GetPropertyInfoArray(type, true);
foreach (var pi in propInfos)
{
if (pi.Name.Equals(propName))
{
var value = pi.GetValue(obj, null);
if (null != value && null != propValue && !propValue.Equals(value))
return true;

return false;
}
}

return false;
}
}
}

原文地址:https://www.cnblogs.com/zunzunQ/p/7580798.html