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

时间:2015-02-03 20:05:09

标签: c# .net enums clr

例如,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版本中存在,并具有相同的含义?

1 个答案:

答案 0 :(得分:1)

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

ECMA-334(C#)在21.3 Enum members中说明......

  

枚举成员的关联值是隐式或显式指定的。如果枚举成员的声明具有常量表达式初始值设定项,则该常量表达式的值(隐式转换为枚举的基础类型)是枚举成员的关联值。如果枚举成员的声明没有初始值设定项,则隐式设置其关联值,如下所示:

     
      
  • 如果枚举成员是枚举类型中声明的第一个枚举成员,则其关联值为零。
  •   
  • 否则,通过将文本上在前的枚举成员的关联值增加1来获得枚举成员的关联值。此增加的值必须在可由基础类型表示的值范围内。
  •   

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

<强>答案:

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