首页 > 代码库 > [C#]利用反射来判断对象是否包含某个属性

[C#]利用反射来判断对象是否包含某个属性

关键代码:

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

代码使用:

            bool cc = _person.ContainProperty("cc");            bool aa = _person.ContainProperty("Age");
<style type="text/css">.csharpcode, .csharpcode pre{ font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em;}.csharpcode .lnum { color: #606060; }</style>希望有所帮助!