How do I define a property to read an attribute from, without instantionating an object?

前端 未结 5 1469
名媛妹妹
名媛妹妹 2021-01-23 10:00

Suppose I have:

class Person
{
[ColumnAttribute(\"ID\"]
    public int Id;
[ColumnAttribute(\"Name\"]
public string Name;
[ColumnAttribute(\"DateOfBirth\"]
    p         


        
5条回答
  •  庸人自扰
    2021-01-23 10:58

    Yep, I defined an extension method, to make it a bit easier, so i can just call typeof(Person).GetAttributes():

            /// 
        /// Loads the configuration from assembly attributes
        /// 
        /// The type of the custom attribute to find.
        /// The calling assembly to search.
        /// An enumeration of attributes of type T that were found.
        public static IEnumerable GetAttributes(this Type typeWithAttributes)
            where T : Attribute
        {
            // Try to find the configuration attribute for the default logger if it exists
            object[] configAttributes = Attribute.GetCustomAttributes(typeWithAttributes,
                typeof(T), false);
    
            // get just the first one
            if (configAttributes != null && configAttributes.Length > 0)
            {
                foreach (T attribute in configAttributes)
                {
                    yield return attribute;
                }
            }
        }
    

提交回复
热议问题