Finding all classes with a particular attribute

后端 未结 2 1680
北荒
北荒 2020-12-03 09:52

I\'ve got a .NET library in which I need to find all the classes which have a custom attribute I\'ve defined on them, and I want to be able to find them on-the-fly when an a

相关标签:
2条回答
  • 2020-12-03 10:15
    IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) 
                                  where TAttribute: System.Attribute
     { return from a in AppDomain.CurrentDomain.GetAssemblies()
              from t in a.GetTypes()
              where t.IsDefined(typeof(TAttribute),inherit)
              select t;
     }
    
    0 讨论(0)
  • 2020-12-03 10:18

    Mark posted a good answer, but here is a linq free version if you prefer it:

        public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : Attribute
        {
            var output = new List<Type>();
    
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
    
            foreach (var assembly in assemblies)
            {
                var assembly_types = assembly.GetTypes();
    
                foreach (var type in assembly_types)
                {
                    if (type.IsDefined(typeof(TAttribute), inherit))
                        output.Add(type);
                }
            }
    
            return output;
        }
    
    0 讨论(0)
提交回复
热议问题