开发者

Is it possible to get the names and values of the members of an enum in D?

开发者 https://www.devze.com 2023-03-22 04:43 出处:网络
I would like to get the names and values from an enum type in D2. I know I can get enum values using std.traits but what about the names?

I would like to get the names and values from an enum type in D2. I know I can get enum values using std.traits but what about the names?

Given:

enum lst
{
  apple,
  bottle,
  orange,
  blue    
}

I would like to get an associative array like.

string lstmap[int] = [1:"apple", 2:"bottle", 3:"orange", 4:"blue"].

The answer is yes. The solution, as someone showed me is:

foreach (i, member; __traits(allMembers, lst)) {开发者_C百科
  lstmap[cast(int) __traits(getMember, lst, member)] = member;
}


foreach (i, member; __traits(allMembers, lst)) {
  lstmap[cast(int) __traits(getMember, lst, member)] = member;
}

(copied from question as community wiki)


In case you want this solely for purposes of value-to-string convertation, consider using std.conv.to!string(lst.orange) — will evaluate to "orange".


      //ENUMList is the name of Enum

        var values = (ENUMList[])Enum.GetValues(typeof(ENUMList));
        var query = from name in values
                    select new EnumData//EnumData is a Modal or Entity
                    {
                        ID = (short)name,
                        Name = GetEnumDescription(name)//Description of Particular Enum Name
                    };
        return query.ToList();
0

精彩评论

暂无评论...
验证码 换一张
取 消