简体   繁体   中英

c# enum constants map to unique integer values

is there any way in c# to ensure enum constants map to unique integer values.

public enum Color
{
None =0,
red = 1,
blue= 2,
white = 3
}

Here if i do change numeric value of "white from 3 to 2" i should get the compilation error.

In my project i'm saving the enum integer value in DB respect to constant. i need a constraint in enum like if someone add a new constant in enum( eg black). user must provide the unique numeric value with enum constant.

thanks

The best thing would be not to explicitly set the values in the enum definition. Put a comment in the enum definition telling anyone adding to it to ensure they only add to the end.

For example:

public enum Color
{
    None,
    red,
    blue,
    white,
    // **NEW ENTRIES MUST ONLY BE ADDED AT THE END OF THE ENUM**
}

Alternatively use the built-in Color structure and its ToArgb( ) method. Or indeed the KnownColor enumeration.

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