Get all ENUM objects in project

2019-09-04 12:07发布

问题:

I have some enum objects at anywhere in my project. They are in same feature. How can I find all enum objects with filter. I don't sure about the filter, but I think we can add an attribute for Enum object and filter type base on the attribute.

For example, I have 2 enum objects in 2 class:

public class FirstClass
{
    [HelloWord]
    public enum FirstEnum
    {
        View = 1,
        Edit = 2
    }
}

public class SecondClass
{
    [HelloWord]
    public enum SecondEnum
    {
        Good,
        Bad
    }
}

So, I want to list all enum object in project that contain attribute [HelloWorld]. How can I do that?

回答1:

Here is a Linq expression that will loop over all the types which are both enums and have your custom 'HelloWorld' attribute on them.

foreach(Type enumType in Assembly.GetExecutingAssembly().GetTypes()
                        .Where(x => x.IsSubclassOf(typeof(Enum)) &&
                               x.GetCustomAttribute<HelloWorldAttribute>() != null))
{
    Console.WriteLine(enumType.Name);
}