C # Custom Attributes from Properties

therefore, I have a set of properties from my class that I want to execute. For each property, I can have custom attributes, so I want to skip them. In this particular case, I have my own attribute for my City Class as such

public class City
{   
    [ColumnName("OtroID")]
    public int CityID { get; set; }
    [Required(ErrorMessage = "Please Specify a City Name")]
    public string CityName { get; set; }
}

Attribute is defined as such

[AttributeUsage(AttributeTargets.All)]
public class ColumnName : System.Attribute
{
    public readonly string ColumnMapName;
    public ColumnName(string _ColumnName)
    {
        this.ColumnMapName= _ColumnName;
    }
}

When I try to iterate over properties [that work great] and then scroll through the attributes, it just ignores the for loop for the attribute and returns nothing.

foreach (PropertyInfo Property in PropCollection)
//Loop through the collection of properties
//This is important as this is how we match columns and Properties
{
    System.Attribute[] attrs = 
        System.Attribute.GetCustomAttributes(typeof(T));
    foreach (System.Attribute attr in attrs)
    {
        if (attr is ColumnName)
        {
            ColumnName a = (ColumnName)attr;
            var x = string.Format("{1} Maps to {0}", 
                Property.Name, a.ColumnMapName);
        }
    }
}

When I go to the immediate window for a property that has a user attribute, I can do

?Property.GetCustomAttributes(true)[0]

He will return ColumnMapName: "OtroID"

It seems to me that this is not suitable for working programmatically, although

+5
source share
4 answers

,

, T typeof (T)?

Property.GetCustomAttribute(true) [0], foreach GetCustomattributes typeparameter.

:

System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(T));

System.Attribute[] attrs = property.GetCustomAttributes(true);

,

+2

, :

PropertyInfo[] propCollection = type.GetProperties();
foreach (PropertyInfo property in propCollection)
{
    foreach (var attribute in property.GetCustomAttributes(true))
    {
        if (attribute is ColumnName)
        {
        }
    }
}
+8

, of (T).

intellisense , Property.

Property.GetCustomAttributes(Boolean) . , LINQ , .

+1

, x "OtroID Maps to CityID".

var props = typeof(City).GetProperties();
foreach (var prop in props)
{
    var attributes = Attribute.GetCustomAttributes(prop);
    foreach (var attribute in attributes)
    {
        if (attribute is ColumnName)
        {
            ColumnName a = (ColumnName)attribute;
            var x = string.Format("{1} Maps to {0}",prop.Name,a.ColumnMapName);
        }
    }
}
+1

All Articles