本地定义的枚举标志和枚举定义的标志有什么区别?

What is the difference between local defined Enum-flags and Enum-defined flags?

当我遇到枚举的 [Flags] 时,我正在使用枚举并寻找一种方法来将一系列枚举值分组以分隔组。

我注意到 ms-Docs 上的示例正在打印本地声明的枚举按位范围的数组(作为枚举名称),但当我在枚举本身中声明相同的范围时却没有。

我已经测试了 Enum.HasFlag() 并且它进行相同的计算,但它不会以相同的方式打印。我已经找到了很多标志迭代器的解决方案,但似乎该功能已经存在于局部声明的变量中。

枚举声明值和本地声明的枚举有什么区别?

[Flags] 
public enum DinnerItems
{
        None = 0,
        Entree = 1,
        Appetizer = 2,
        Side = 4,
        Dessert = 8,
        Beverage = 16,
        BarBeverage = 32,
        MyOrder = Appetizer | Entree | Beverage | Dessert,
}

 DinnerItems flagValue = DinnerItems.None | DinnerItems.Side;

            DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
                                 DinnerItems.Beverage | DinnerItems.Dessert;

            Console.WriteLine("{0} includes {1}: {2}",
                            myOrder, flagValue, myOrder.HasFlag(flagValue));

这将打印: MyOrder 包括 Side: False

从枚举中删除 DinnerItems.MyOrder 时的相同代码: 主菜、开胃菜、甜点、饮料包括配菜:错误

根据the docs

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.

如果没有 MyOrder,它会生成 delimiter-separated 名称列表 - 这似乎是您想要的。

但是 with MyOrder - 现在 MyOrder 是一个或多个命名常量的最简单组合(一个常量,四个) - 所以它改为输出 MyOrder