C# DescriptionAttribute 取值

 public static class Extensions
    {
      
        public static string GetDescription(this object obj, string name)
        {  
                var referencedType = obj.GetType(); 
                return GetDescription(referencedType, name);
        }

        public static string GetDescription(Type referencedType, string propertyName)
        {
            //	gets the properties of the referenced type
            PropertyDescriptorCollection properties
                = TypeDescriptor.GetProperties(referencedType);

            if (properties != null)
            {

                // gets a PropertyDescriptor to the specific property.
                PropertyDescriptor property = properties[propertyName];
                if (property != null)
                {
                    //  gets the attributes of the required property
                    AttributeCollection attributes = property.Attributes;

                    // Gets the description attribute from the collection.
                    DescriptionAttribute descript
                        = (ObjectDescriptionAttribute)attributes[typeof(ObjectDescriptionAttribute)];

                    // register the referenced description
                    if (!String.IsNullOrEmpty(descript.Description))
                    { return descript.Description; }
                }

            }

            return string.Empty;
        }

}

 

posted @ 2014-01-14 04:09  bert.zeng  阅读(2732)  评论(1编辑  收藏  举报