首页 > 其他 > 详细

反射的属性获取与设置

时间:2017-09-23 13:04:37      阅读:320      评论:0      收藏:0      [点我收藏+]

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;
}
}
}

反射的属性获取与设置

原文:http://www.cnblogs.com/zunzunQ/p/7580798.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!