简体   繁体   中英

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

For example, System.Windows.VerticalAlignment is defined like this:

// 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,
}

So, is it safe to serialize a value of this type as 0, 1, 2, or 3? That is, are those values guaranteed to exist in future .Net versions, and have the same meaning?

The example contains explicitly declared values, so they would never change even if you reordered the rows. Also, the value of every enum value is determined at compile-time, so it can not change without a recompilation of your assembly.

ECMA-334 (C#) states in 21.3 Enum members that...

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.

You can inadvertently change an enum value if you use implicit values, and 1) reorder the values, 2) introduce a new member preceding your value, or 3) change the value of a member preceding your value.

Answer:

You specifically ask about custom serialization of an enum value as it's underlying integer value. There is no guarantee within .NET that the values will stay unchanged, but changing deployed enums is a breaking change which will most probably never occur.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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