• 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 = _person.ContainProperty("cc");
    bool aa = _person.ContainProperty("Age");
  • 相关阅读:
    文化因素对商标翻译的影响
    Building An Effective Marketing Plan
    HipHop PHP简介(转)
    关于comet
    TI BSL in python
    剖析 HTTP 协议
    NSIS 打包脚本基础
    图解使用VS的安装项目打包程序
    [Java IO]06_JSON操作
    [Java IO]04_系统标准IO
  • 原文地址:https://www.cnblogs.com/rinack/p/5227111.html
Copyright © 2020-2023  润新知