Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取项目中的所有枚举对象_C#_Reflection_Enums - Fatal编程技术网

C# 获取项目中的所有枚举对象

C# 获取项目中的所有枚举对象,c#,reflection,enums,C#,Reflection,Enums,我在项目的任何地方都有一些枚举对象。它们具有相同的特征。如何使用筛选器查找所有枚举对象。我不确定过滤器,但我认为我们可以为Enum对象和基于该属性的过滤器类型添加一个属性 例如,我在2类中有2个枚举对象: public class FirstClass { [HelloWord] public enum FirstEnum { View = 1, Edit = 2 } } public class SecondClass {

我在项目的任何地方都有一些枚举对象。它们具有相同的特征。如何使用筛选器查找所有枚举对象。我不确定过滤器,但我认为我们可以为Enum对象和基于该属性的过滤器类型添加一个属性

例如,我在2类中有2个枚举对象:

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

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

所以,我想列出项目中包含属性[HelloWorld]的所有枚举对象。我该怎么做呢?

这里有一个Linq表达式,它将在所有类型上循环,这些类型都是枚举,并且具有自定义的“HelloWorld”属性

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

这里有一个Linq表达式,它将循环遍历所有类型,这些类型都是枚举,并且具有自定义的“HelloWorld”属性

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

Assembly.getExecutionGassembly()
可能不是OP想要的程序集。@DannyChen OP说“它们具有相同的功能”并且在“我的项目”中,所以我最好的猜测是它是正在执行的程序集。@Danny Chen:你有什么建议吗?
Assembly.getExecutionGassembly()
可能不是OP想要的程序集。@DannyChen OP说“它们在同一个功能中”并且在“我的项目”中,所以我最好的猜测是它是正在执行的程序集。@Danny Chen:你有什么建议吗?