框架枚举的整数值是否保证在 .Net 版本中保持不变?

Are the Integer values of framework enums guaranteed to stay the same across .Net versions?

例如System.Windows.VerticalAlignment是这样定义的:

// Summary:
//     Describes how a child element is vertically positioned or stretched within
//     a parent's layout slot.
public enum VerticalAlignment
{
    // Summary:
    //     The element is aligned to the top of the parent's layout slot.
    Top = 0,
    //
    // Summary:
    //     The element is aligned to the center of the parent's layout slot.
    Center = 1,
    //
    // Summary:
    //     The element is aligned to the bottom of the parent's layout slot.
    Bottom = 2,
    //
    // Summary:
    //     The element is stretched to fill the entire layout slot of the parent element.
    Stretch = 3,
}

那么,将这种类型的值序列化为 0、1、2 或 3 是否安全?也就是说,这些值是否保证在未来的 .Net 版本中存在,并且具有相同的含义?

该示例包含显式声明的值,因此即使您对行重新排序,它们也永远不会改变。此外,每个枚举值的值都是在编译时确定的,因此如果不重新编译程序集就无法更改。

ECMA-334 (C#) 在 21.3 Enum members 中指出...

The associated value of an enum member is assigned either implicitly or explicitly. If the declaration of the enum member has a constant-expression initializer, the value of that constant expression, implicitly converted to the underlying type of the enum, is the associated value of the enum member. If the declaration of the enum member has no initializer, its associated value is set implicitly, as follows:

  • If the enum member is the first enum member declared in the enum type, its associated value is zero.
  • Otherwise, the associated value of the enum member is obtained by increasing the associated value of the textually preceding enum member by one. This increased value must be within the range of values that can be represented by the underlying type.

如果您使用隐式值,您可能会无意中更改枚举值,并且 1) 重新排序这些值,2) 在您的值之前引入一个新成员,或 3) 更改您的值之前的成员的值。

答案:

您特别询问枚举值的自定义序列化,因为它是基础整数值。在 .NET 中无法保证值将保持不变,但更改已部署的枚举是一项重大更改,很可能 永远不会发生。