反射的属性获取与设置
Posted 我心永恒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了反射的属性获取与设置相关的知识,希望对你有一定的参考价值。
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;
}
}
}
以上是关于反射的属性获取与设置的主要内容,如果未能解决你的问题,请参考以下文章