使用 EnumMember 属性遍历枚举

Iterating through enum with EnumMember attribute

鉴于以下 enum

public enum JobTypes
{
    [EnumMember (Value = "IN PROGRESS")]
    IN_PROGRESS,
    SUBMITTED,
    [EnumMember (Value = "IN REVIEW")]
    IN_REVIEW
}

我正在按如下方式迭代这些:

foreach (var jobType in Enum.GetValues (typeof(JobTypes))) {
    Console.WriteLine("{0,3:D} 0x{0:X} {1}", Enum.Parse(typeof(JobTypes), jobType.ToString()), jobType);
}

输出:

// The example displays the following output: 
// 0     0x00000000     IN_PROGRESS 
// 1     0x00000001     SUBMITTED
// 2     0x00000002     IN_REVIEW

预期:

// The example displays the following output: 
// 0     0x00000000     IN PROGRESS // no _ character 
// 1     0x00000001     SUBMITTED
// 2     0x00000002     IN REVIEW // no _ character

EnumMemberNameAttribute只影响序列化:

The EnumMemberAttribute enables fine control of the names of the enumerations as they are serialized.

它对调用 ToString() 值的结果没有任何影响,这实际上就是您在这里所做的。