mardi 27 novembre 2018

C# Get List of All Classes with Specific Attribute Parameter

I'm trying to get a list of all Classes with a specific Attribute and Enum parameter of the Attribute.

View my example below. I realize how to get all Classes with Attribute GenericConfig, however how do I then filter down on parameter?

namespace ConsoleApp1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // get me all classes with Attriubute GenericConfigAttribute and Parameter Type1
            var type1Types =
                    from type in Assembly.GetExecutingAssembly().GetTypes()
                    where type.IsDefined(typeof(GenericConfigAttribute), false)
                    select type;

            Console.WriteLine(type1Types);
        }
    }

    public enum GenericConfigType
    {
        Type1,
        Type2
    }

    // program should return this class
    [GenericConfig(GenericConfigType.Type1)]
    public class Type1Implementation
    {
    }

    // program should not return this class
    [GenericConfig(GenericConfigType.Type2)]
    public class Type2Implementation
    {
    }

    [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
    public class GenericConfigAttribute : Attribute
    {
        public GenericConfigType MyEnum;

        public GenericConfigAttribute(GenericConfigType myEnum)
        {
            MyEnum = myEnum;
        }
    }
}





Aucun commentaire:

Enregistrer un commentaire