GetName for enum with duplicate values

后端 未结 5 1638
小鲜肉
小鲜肉 2020-12-07 00:46

If I have duplicate values in a C# enum, saying

enum MyE {
  value1 = 1,
  value2 = 2,
  valued = 1
}

What should be the values of the foll

5条回答
  •  春和景丽
    2020-12-07 01:45

    Well, because there are no guarantees about the order and obsolete attribute seems to have no impact on Enum methods, I would usually suggest to use a string property for serialization purpose and use custom code to handle obsolete values.

    That way, the primary Enum has no duplicate and contains only current values.

    Depending on the serialization framework, you might be able to mark the string property as serializable but obsolete and the actual property used in code to be ignored by serialization.

    To handle obsolete values in the string property setter, you can either use an [Obsolete] enum or a switch statement. Typically, I would probably use the former if I have a lot of obsolete values to handle and the latter if I have only a few values to handle.

    Also it might make sense to put the code in an helper class or an extension method particularly if you load or store that value from a bunch of places.

    Although I have not tried it much in production code, I am wondering if it would be better to use a struct instead of an enum to have more control... but I think it need a lot of boilerplate code that cannot easily be made generic.

提交回复
热议问题