Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all classes with a specific attribut [duplicate]

Tags:

c#

attributes

Possible Duplicate:
Finding all classes with a particular attribute

In an assembly I would like to get all instances of a particular class attribute. In other words I would like to have the list of classes that have a specific attribute.

Normally you would have a class for which you can fetch the attribute using the GetCustomAttributes method.

Is it possible to have a list of who has a particular attribute?

like image 692
mathk Avatar asked Jan 21 '13 14:01

mathk


1 Answers

public static IEnumerable<Type> GetTypesWithMyAttribute(Assembly assembly)
{
    foreach(Type type in assembly.GetTypes())
    {
        if (Attribute.IsDefined(type, typeof(MyAttribute)))
            yield return type;
    }
}

Or:

public static List<Type> GetTypesWithMyAttribute(Assembly assembly)
{
    List<Type> types = new List<Type>();

    foreach(Type type in assembly.GetTypes())
    {
        if (type.GetCustomAttributes(typeof(MyAttribute), true).Length > 0)
            types.Add(type);
    }

    return types;
}

Linq VS my method benchmark (100000 iterations):

Round 1
My Approach:     2088ms
Linq Approach 1: 7469ms
Linq Approach 2: 2514ms

Round 2
My Approach:     2055ms
Linq Approach 1: 7082ms
Linq Approach 2: 2149ms

Round 3
My Approach:     2058ms
Linq Approach 1: 7001ms
Linq Approach 2: 2249ms

Benchmark code:

[STAThread]
public static void Main()
{
    List<Type> list;

    Stopwatch watch = Stopwatch.StartNew();

    for (Int32 i = 0; i < 100000; ++i)
        list = GetTypesWithMyAttribute(Assembly.GetExecutingAssembly());

    watch.Stop();

    Console.WriteLine("ForEach: " + watch.ElapsedMilliseconds);

    watch.Restart();

    for (Int32 i = 0; i < 100000; ++i)
        list = GetTypesWithMyAttributeLinq1(Assembly.GetExecutingAssembly());

    Console.WriteLine("Linq 1: " + watch.ElapsedMilliseconds);

    watch.Restart();

    for (Int32 i = 0; i < 100000; ++i)
        list = GetTypesWithMyAttributeLinq2(Assembly.GetExecutingAssembly());

    Console.WriteLine("Linq 2: " + watch.ElapsedMilliseconds);

    Console.Read();
}

public static List<Type> GetTypesWithMyAttribute(Assembly assembly)
{
    List<Type> types = new List<Type>();

    foreach (Type type in assembly.GetTypes())
    {
        if (Attribute.IsDefined(type, typeof(MyAttribute)))
            types.Add(type);
    }

    return types;
}

public static List<Type> GetTypesWithMyAttributeLinq1(Assembly assembly)
{
    return assembly.GetTypes()
               .Where(t => t.GetCustomAttributes().Any(a => a is MyAttribute))
               .ToList();
}

public static List<Type> GetTypesWithMyAttributeLinq2(Assembly assembly)
{
    return assembly.GetTypes()
               .Where(t => Attribute.IsDefined(t, typeof(MyAttribute)))
               .ToList();
}
like image 75
Tommaso Belluzzo Avatar answered Nov 16 '22 01:11

Tommaso Belluzzo