简体   繁体   English

是标志枚举的字符串表示形式中定义的值的顺序

[英]is the order of values defined in the string representation of a flags enum

[flags]
enum Test
{
  a=0,
  b=1,
  c=2
}
...
var v = Test.c | Test.b;
var str = v.ToString();
// str = 'b, c'

is the order of the values in 'str' defined. 是'str'中定义的值的顺序。 Both b, c and c, b are semantically the same by syntactically different. b,c和c,b在语法上都相同,但在语法上不同。 Why do I care - I am writing test code (not in c#) would prefer to not have to do fancy logic parsing all possible combinations 我为什么在乎-我正在编写测试代码(不在C#中编写),所以不希望不必花哨的逻辑来解析所有可能的组合

The documentation for Enum.ToString says Enum.ToString文档

If the FlagsAttribute is applied and there is a combination of one or more named constants equal to the value of this instance, then the return value is a string containing a delimiter-separated list of the names of the constants. 如果应用了FlagsAttribute,并且存在一个或多个等于此实例值的命名常量的组合,则返回值是一个包含定界符分隔的常量名称列表的字符串。

It does not specify in what order they will be shown. 它没有指定将以什么顺序显示它们。

The code that does the formatting (see the function InternalFlagsFormat in the reference source, here: http://referencesource.microsoft.com/#mscorlib/system/enum.cs ) appears to always work the same way. 进行格式化的代码(请参见参考源中的InternalFlagsFormat函数,在这里: http : //referencesource.microsoft.com/#mscorlib/system/enum.cs )似乎总是以相同的方式工作。

But, because the order isn't documented, you'll have to judge for yourself how likely it is to change. 但是,由于未记录订单,因此您必须自己判断更改的可能性。 Having been burned in the past by assuming that things wouldn't change, I'd be real wary of depending on anything that's not explicitly documented. 过去,我假设事情不会改变,因此被烧死了,我会非常谨慎地依赖未明确记录的任何内容。

EDIT by OP: there is an interesting comment in the code that formats the output OP编辑:在格式化输出的代码中有一个有趣的注释

 // These values are sorted by value. Don't change this
    String[] names;
    ulong[] values;

this suggests that the enum names will come out in order of the enum values. 这表明枚举名称将按枚举值的顺序出现。 Although as you say - its not guranteed from version to version 尽管正如您所说-版本之间不保证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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