vendredi 14 décembre 2018

Recursively search Properties in class decorated by attribute

I would like to get all properties decorated by attribute AggregateAuthorizeIdentifier. It is core functionallity, so should be as fast as posible.

I can search recurvicvely via all properties but I would check all System and 3rd parties libs. But it isn't optimal solution.

Have you met with such a problem?

public class ReadOrderHistoryQuery
{
    public List<string> Ordering { get; set; }

    public Criteria Criteria { get; set; }

    public class Criteria
    {
        [AggregateAuthorizeIdentifier]
        public int UserId { get; set; }

        public string InvoiceId { get; set; }
    }
}

my solution:

    static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(object command)
    {
        var attributedProperties = GetAuthorizeIdentifierAttribute(command.GetType());
        return attributedProperties;
    }
    static IEnumerable<PropertyWithAttribute> GetAuthorizeIdentifierAttribute(Type type)
    {
        //check current property
        var result = type.GetProperties()
            .Where(prop => Attribute.IsDefined(prop, typeof(AggregateAuthorizeIdentifierAttribute)))
            .Select(p => new PropertyWithAttribute()
            {
                Property = p,
                Attribute = p.GetCustomAttribute<AggregateAuthorizeIdentifierAttribute>(true)
            })
            .ToList();
        //deeper check all properties
        result.AddRange(type.GetProperties()
            .SelectMany(p => GetAuthorizeIdentifierAttribute(p.PropertyType)));
        return result;
    }





Aucun commentaire:

Enregistrer un commentaire