简体   繁体   中英

CA1008: Enums should have zero value and Flag enums

even when I'm completely aware of why the CA1008 warning exists I don't know how to avoid it in the following situation. I have a Flag enum with the following meanings:

ValidValue = 0x01
WrittenValue = 0x02

So in this case 0 means InvalidValueNonWritten instead of None. The rule says

Do not suppress a warning from this rule except for flags-attributed enumerations that have previously shipped.

In this case I've not shipped the enum so how can I prevent this warning?

EDIT:

The warning explicitily says:

Warning 86 CA1008 : Microsoft.Design : In enum 'XXX', change the name of 'XXX.InvalidValueNonWritten' to 'None'.

EDIT 2:

More states of the enum:

CommandValue = 0x04 // Otherwise it is DataValue
InmediateValue = 0x08 // Otherwise it is Deferred

At this particular moment, the 0 value has a "not valid or written" meaning. However, this will no longer be the case if you add more enum members. For example, if you add ApprovedValue = 0x04 , 0 will start to mean "not valid or written or approved". This is the main reason for always using a None name for the 0 value.

If None doesn't make sense as a name, this usually signals a flaw in the enum design or name. In your case, it sounds like the enum actually represents steps that the value has passed through, as opposed to state of the value (for which a flags enum wouldn't typically be used). Might the following be a closer representation of what you intend (where an associated class might have a property named something like CompletedValueProcessingSteps )?

[Flags]
enum ValueProcessingSteps
{
    None = 0,
    Validation = 1,
    Writing = 2
}

If 0 means InvalidValueNonWritten then add InvalidValueNonWritten into the enum. Then this warning won't happen. If you really shouldn't have 0 in your enum suppress the warning in code and ensure you put the justification in for future reference.

If you are expecting an exception due to 0 not been valid it is better to perform the validation in your method using the enum. Also this is better for serialization, for example if you are using serialization on models the model will de-serialize with a missing member from the source.

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