简体   繁体   中英

Printing list of enums in a particular namespace C#

Is there a way to print all the enums in C# class library or namespace? I want the name to be printed with its values.

For example if I have the namespace as below:

namespace MyCompany.SystemLib
{
    public enum ItemStatus
    {
        None = 0,
        Active = 1,
        Inactive = 2    
    }

    public enum MyEnum
    {
        EnumVal1 = 1,
        EnumVal2 = 2,
        EnumVal3 = 3,

    }   
}

I would like to print them delimited as below (to a textfile) Bullet given for clarity here not needed in output.

  • ItemStatus,None=0,Active=1,Inactive=1
  • MyEnum,EnumVal1=1,EnumVal2=2,EnumVal3

I don't know where to start. Any help is appreciated.

Reflection to the rescue!

List<string> allEnums = new List<string>();
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes());

foreach (Type type in allTypes)
{
    if (type.Namespace == "MyCompany.SystemLib" && type.IsEnum)
    {
        string enumLine = type.Name + ",";
        foreach (var enumValue in Enum.GetValues(type))
        {
            enumLine += enumValue + "=" + ((int)enumValue).ToString() + ",";
        }

        allEnums.Add(enumLine);
    }
}

The first line goes over all assemblies currently loaded in memory (because a namespace can be scattered over many DLLs and EXEs) and filters out those in the right namespace, and that are enums. This can be streamlined into a LINQ query if you'd like.

The inner loop goes over the values of the enum, and uses GetName to match the string to the value.

尝试使用Enum.GetNames()方法。

It can be done using LINQ and Reflection ofcourse.

var asm = Assembly.LoadFrom("path of the assembly");
var enums = asm.GetTypes().Where(x => x.IsEnum).ToList();

var result = enums
            .Select(
                x =>
                    string.Format("{0},{1}", x.Name,
                        string.Join(",",Enum.GetNames(x)
                        .Select(e => string.Format("{0}={1}", e, (int)Enum.Parse(x, e))))));

File.WriteAllLines("path", result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM