zoukankan      html  css  js  c++  java
  • 反射的属性获取与设置

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

  • 相关阅读:
    QQ空间爬虫--获取好友信息
    分层最短路-2018南京网赛L
    安装SSH,配置SSH无密码登陆
    树形DP--求树上任意两点间距离和
    JTS基本概念和使用
    odps编写UDF的实现
    oozie安装总结
    同步工具的选择
    转:hive面试题
    转:hive-列转行和行转列
  • 原文地址:https://www.cnblogs.com/zunzunQ/p/7580798.html
Copyright © 2011-2022 走看看