开发者

Any suggestions for defining the order of the array returned from Attribute.GetCustomAttributes

开发者 https://www.devze.com 2023-03-08 06:35 出处:网络
Ok... so the title defines exactly what I\'m looking for. Right now, I am using this solution for controlling the order:

Ok... so the title defines exactly what I'm looking for.

Right now, I am using this solution for controlling the order:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class DefaultSortCriterionAttribute : Attribute
{
    private int _priority = 0;

    public int Priority
    {
        get
        {
            return _priority;
        }
    }

    private string _parameterName;

    public string ParameterName
    {
        get
        {
            return _parameterName;
        }
    }

    private SortDirection _direction;

    public SortDirection Direction
    {
        get
        {
            return _direction;
        }
    }

    public DefaultSortCriterionAttribute(string parameterName, SortDirection direction)
    {
        _parameterName = parameterName;
        _direction = direction;
    }

    public DefaultSortCriterionAttribute(int priority, string parameterName, SortDirection direction)
    {
        _priority = priority;
        _parameterName = parameterName;
        _direction = direction;
    }

}

Any suggestion how to make it more efficient?

Example of the usage in my generic class:

Type type = typeof(T);
if (Attribute.IsDefined(type, typeof(DefaultSortCriterionAttribute)))
{
    DefaultSortCriterionAttribute[] attribs = (DefaultSortCriterionAttribute[])Attribute.GetCustomAttributes(type, typeof(DefaultSortCriterionAttribute));

    List<SortCriterion> list = new List<SortCriterion>();

    foreach (DefaultSortCriterionAttribute attrib in attribs)
    {
        SortCriterion sc = new SortCri开发者_StackOverflow中文版terion(attrib.ParameterName, attrib.Direction);
        list.Add(sc);
    }

    return this.CompareTo(other, list);
}


I can't imagine a better approach. This is good.

0

精彩评论

暂无评论...
验证码 换一张
取 消