码迷,mamicode.com
首页 > Windows程序 > 详细

C#利用反射来判断对象是否包含某个属性的实现方法

时间:2016-02-29 14:07:15      阅读:318      评论:0      收藏:0      [点我收藏+]

标签:

    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");

 

C#利用反射来判断对象是否包含某个属性的实现方法

标签:

原文地址:http://www.cnblogs.com/rinack/p/5227111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!