How to access the Description attribute on either a property or a const in C#?

前端 未结 4 1415
死守一世寂寞
死守一世寂寞 2020-12-15 05:33

How do you access the Description property on either a const or a property, i.e.,

public static class Group
{

    [Description( \"Specified parent-child rel         


        
4条回答
  •  天命终不由人
    2020-12-15 06:39

    Here is a helper class I am using for processing custom attributes in .NET

    public class AttributeList : List
    {
        /// 
        /// Gets a list of custom attributes
        /// 
        /// 
        /// 
        public static AttributeList GetCustomAttributeList(ICustomAttributeProvider propertyInfo)
        {
            var result = new AttributeList();
            result.AddRange(propertyInfo.GetCustomAttributes(false).Cast());
            return result;
        }
    
        /// 
        /// Finds attribute in collection by its type
        /// 
        /// 
        /// 
        public T FindAttribute() where T : Attribute
        {
            return (T)Find(x => typeof(T).IsAssignableFrom(x.GetType()));
        }
    
        public bool IsAttributeSet() where T : Attribute
        {
            return FindAttribute() != null;
        }
    }
    

    Also unit tests for MsTest showing how to use this class

    [TestClass]
    public class AttributeListTest
    {
        private class TestAttrAttribute : Attribute
        {
        }
    
        [TestAttr]
        private class TestClass
        {
        }
    
        [TestMethod]
        public void Test()
        {
            var attributeList = AttributeList.GetCustomAttributeList(typeof (TestClass));
            Assert.IsTrue(attributeList.IsAttributeSet());
            Assert.IsFalse(attributeList.IsAttributeSet());
            Assert.IsInstanceOfType(attributeList.FindAttribute(), typeof(TestAttrAttribute));
        }
    }
    

    http://www.kozlenko.info/2010/02/02/getting-a-list-of-custom-attributes-in-net/

提交回复
热议问题