C# enum ToString() 是否保证 return 枚举名称?
Is C# enum ToString() guaranteed to return enum name?
enum Flags
{
Foo,
Bar
}
Flags.Foo.ToString()
是否保证return"Foo"?或者我必须使用 Enum.GetName(...)?
如果枚举值恰好与枚举项匹配,则可以。
但要注意这样的情况:
var test = (Flags)(-1);
// test.ToString() == "-1"
如果该值与枚举项不匹配,它只会 return 作为字符串的基础值。默认情况下,枚举的基础数据类型是 int
.
此外,如果您的枚举是用 [Flags]
定义的,如下所示:
[Flags]
enum Flags
{
Foo = 1,
Bar = 2
}
然后ToString()
可以return一个逗号分隔的标志列表:
var test = Flags.Foo | Flags.Bar;
// test.ToString() == "Foo, Bar"
就像 Orace 在评论中指出的那样,如果值不明确,即如果多个枚举项可以匹配该值,则您不应该对将选择哪一个做出任何假设。
The return value is formatted with the general format specifier ("G"). That is, if the FlagsAttribute is not applied to this enumerated type and there is a named constant equal to the value of this instance, then the return value is a string containing the name of the constant. 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. Otherwise, the return value is the string representation of the numeric value of this instance.
来自 MSDN
enum Flags
{
Foo,
Bar
}
Flags.Foo.ToString()
是否保证return"Foo"?或者我必须使用 Enum.GetName(...)?
如果枚举值恰好与枚举项匹配,则可以。
但要注意这样的情况:
var test = (Flags)(-1);
// test.ToString() == "-1"
如果该值与枚举项不匹配,它只会 return 作为字符串的基础值。默认情况下,枚举的基础数据类型是 int
.
此外,如果您的枚举是用 [Flags]
定义的,如下所示:
[Flags]
enum Flags
{
Foo = 1,
Bar = 2
}
然后ToString()
可以return一个逗号分隔的标志列表:
var test = Flags.Foo | Flags.Bar;
// test.ToString() == "Foo, Bar"
就像 Orace 在评论中指出的那样,如果值不明确,即如果多个枚举项可以匹配该值,则您不应该对将选择哪一个做出任何假设。
The return value is formatted with the general format specifier ("G"). That is, if the FlagsAttribute is not applied to this enumerated type and there is a named constant equal to the value of this instance, then the return value is a string containing the name of the constant. 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. Otherwise, the return value is the string representation of the numeric value of this instance.
来自 MSDN