获取项目中的所有ENUM对象 [英] Get all ENUM objects in project
问题描述
我在项目的任何地方都有一些枚举对象。它们具有相同的功能。如何找到所有带过滤器的枚举对象。我不确定过滤器,但我认为我们可以为Enum对象添加一个属性,并根据该属性添加过滤器类型。
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.
例如,我有2个枚举2类中的对象:
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
}
}
因此,我想列出项目中所有包含属性[HelloWorld]的枚举对象。我该怎么办?
So, I want to list all enum object in project that contain attribute [HelloWorld]. How can I do that?
推荐答案
这是一个Linq表达式,它将遍历所有枚举类型并包含您的自定义'HelloWorld'属性。
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);
}
这篇关于获取项目中的所有ENUM对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!