【发布时间】:2013-05-06 09:10:42
【问题描述】:
给定以下枚举:
[Flags]
public enum Intervals
{
Root = PerfectUnison,
Unison = PerfectUnison,
PerfectUnison = 1 << 0,
AugmentedUnison = MinorSecond,
MinorSecond = 1 << 1,
Second = MajorSecond,
MajorSecond = 1 << 2,
AugmentedSecond = MinorThird,
MinorThird = 1 << 3,
Third = MajorThird,
MajorThird = 1 << 4,
AugmentedThird = PerfectFourth,
DoubleAugmentedThird = Triton,
DiminishedFourth = MajorThird,
Fourth = PerfectFourth,
PerfectFourth = 1 << 5,
AugmentedFourth = Triton,
DoubleAugmentedFourth = PerfectFifth,
Triton = 1 << 6,
//...Removed for brevity, see link to code bellow
}
我正在尝试这个简单的测试:
static void Main(string[] args)
{
var values = Enum.GetValues(typeof(Intervals));
foreach (var value in values)
{
Console.WriteLine(value);
}
}
这是输出:
PerfectUnison、PerfectUnison、PerfectUnison、AugmentedUnison、AugmentedUnison、Second、Second、MinorThird、MinorThird、DiminishedFourth、DiminishedFourth、DiminishedFourth、AugmentedThird、AugmentedThird、AugmentedThird、AugmentedThird、DoubleDiminishedSixth、DoubleDiminishedSixth 等。
虽然我希望为相同值选择的枚举名称具有以下顺序:
根音,MinorSecond,Second,MinorThird,Third,Fourth,Triton,Fifth,MinorSixth,Sixth,MinorSeventh,Seventh,Octave,MinorNinth,Ninth,Tenth,11th,MajorEleventh,13
一个好的复制品也是Enum.GetNames。我希望上述组的名称应始终位于其值匹配名称之前。
我基本上是在寻找每个值的枚举名称的优先级/优先级规则的文档。
您可以在此处使用代码:http://rextester.com/EJOWK87857。
更新
我现在正在研究反编译的Enum.GetNames。看起来它使用反射。那么问题来了,“如何控制反射场的顺序?”。
【问题讨论】:
-
AFAIK,这真的不可能。例如,Enum.GetName 方法特别提到,在检索具有重复值的枚举名称时,您不应该依赖一致的结果。您可以使用
Enum.GetNames(它确实返回您想要的值)并使用这些名称然后使用Enum.Parse 方法按顺序检索值。编辑:但Parse的结果仍然是重复的,而不是原件;不确定这是否有帮助。 -
@ChrisSinclair 我现在正在研究反编译的
Enum.GetNames。看起来它使用反射。那么问题来了,“如何控制反射场的顺序?”。