开发者

Why does enum.ToString() give a different result than what's shown in the debugger tooltip?

开发者 https://www.devze.com 2022-12-16 00:20 出处:网络
Test program (.NET 2.0): [Flags] enum MyEnum { Member1 = 1, Member2 = 2, } class Program { // Inspecting r shows \"Member1 | Member2\"

Test program (.NET 2.0):

[Flags]
enum MyEnum
{
    Member1 = 1,
    Member2 = 2,
}

class Program
{
    // Inspecting r shows "Member1 | Member2"
    MyEnum r = MyEnum.Member1 | MyEnum.Member2;

    // s = "Member1, Member2"
    string s = r.ToString();
}

I would have expected .ToString() to return a string with the members separated by a pipe, but开发者_如何学Go that's not the case.

Bonus info: calling Enum.Parse() on the comma-separated string succeeds, while supplying it with a pipe-separated string fails.


The VS debugger uses visualizers to display values. Only if there's no visualizer for a specific datatype, it will fallback to the .ToString() method.

More info on visualizers:

http://msdn.microsoft.com/en-us/library/zayyhzts.aspx


The default ToString implementation for an enum marked with FlagsAttribute is a comma-separated list. However, it is not necessarily the ToString result that is shown in the debugger - there must be a Debugger Visualizer set up for enums that renders the values with the bitwise OR symbol or pipe.

0

精彩评论

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