zoukankan      html  css  js  c++  java
  • C#利用反射来判断对象是否包含某个属性的实现方法

    public static class SerializeLibrary
        {
            /// <summary>
            /// 利用反射来判断对象是否包含某个属性
            /// </summary>
            /// <param name="instance">object</param>
            /// <param name="propertyName">需要判断的属性</param>
            /// <returns>是否包含</returns>
            public static bool ContainProperty(this object instance, string propertyName)
            {
                if (instance != null && !string.IsNullOrEmpty(propertyName))
                {
                    PropertyInfo _findedPropertyInfo = instance.GetType().GetProperty(propertyName);
                    return (_findedPropertyInfo != null);
                }
                return false;
            }
    
            /// <summary>
            /// 获取对象属性值
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            /// <param name="propertyname"></param>
            /// <returns></returns>
            public static string GetObjectPropertyValue<T>(T t, string propertyname)
            {
                Type type = typeof(T);
                PropertyInfo property = type.GetProperty(propertyname);
                if (property == null)
                {
                    return string.Empty;
                }
                object o = property.GetValue(t, null);
                if (o == null)
                {
                    return string.Empty;
                }
                return o.ToString();
            }
    
            /// <summary>
            /// 获取属性列表
            /// </summary>
            /// <typeparam name="T"></typeparam>
            public static void GetObjectProperty<T>()
            {
                Type t = typeof(T);
                System.Reflection.PropertyInfo[] properties = t.GetProperties();
                foreach (System.Reflection.PropertyInfo info in properties)
                {
                    Console.Write("name=" + info.Name + ";" + "type=" + info.PropertyType.Name + ";value=" + GetObjectPropertyValue<Object>(new object(), info.Name) + "<br />");
                }
            }
        }

    代码使用方法如下:

    bool cc =ContainProperty("cc");
    bool aa =ContainProperty("Age");
  • 相关阅读:
    MPLS 知识要点1
    ISIS的SSN和SRM标志
    对比ISIS和OSPF
    ISIS帧中继实验
    ISIS 认证实验
    ISIS数据库同步
    ISIS Lab 路由泄露
    ISIS Lab 重分布直连
    32、端口有效范围是多少到多少?
    33、为何需要把 TCP/IP 协议栈分成 5 层(或7层)?开放式回答。
  • 原文地址:https://www.cnblogs.com/wu-peng/p/10882080.html
Copyright © 2011-2022 走看看