Objective-C / C 给出枚举默认值
我在某处读到过关于给枚举默认值的内容,如下所示:
typedef enum {
MarketNavigationTypeNone = 0,
MarketNavigationTypeHeirachy = 1,
MarketNavigationTypeMarket = 2
} MarketNavigationLevelType;
..但我不记得这样做的价值。如果我不给它们默认值 - 然后有人稍后重新排序枚举 - 风险是什么?
如果我总是使用枚举名称,甚至不通过它们的整数值来引用它们,是否有任何风险?
我能想到的唯一可能的问题是,如果我从数据库中的 int 值初始化枚举 - 并且枚举被重新排序 - 那么应用程序就会崩溃。
I read somewhere about giving enums default values like so:
typedef enum {
MarketNavigationTypeNone = 0,
MarketNavigationTypeHeirachy = 1,
MarketNavigationTypeMarket = 2
} MarketNavigationLevelType;
.. but i can't remember the value of doing this. If i don't give them default values - and then someone later on reorders the enum - what are the risks?
If i always use the enum name and don't even refer to them by their integer value, is there any risks?
The only possible problem i can think of is if i'm initialising an enum from an int value from a DB - and the enum is reordered - then the app would break.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是默认值,您为他们提供了他们将始终拥有的值。
如果您不显式初始化它们,则第一个枚举器值为零。对于所有其他的,如果没有初始化器,它们的值是前一个枚举器的值加一。
为它们提供明确的值有两个原因:
如果您总是通过它们的值来引用它们名称并且从不显式使用整数值进行比较或赋值,不需要显式地给它们一个值。
That are not default values, you are giving them the values they will always have.
If you wouldn't initialize them explicitly, the first enumerators value is zero. For all others, if there is no initializer, their value is the value of the previous enumerator increased by one.
There are two reasons for giving them explicit values:
If you always refer to them by their name and never explicitly use an integral value for comparison or assignment, explicitly giving them a value is not needed.
一般来说,只有当枚举暴露于某种外部 API 或者它将用于通过数据文件或其他方式交换数据时,这才重要。如果枚举仅在您的应用程序中使用,而没有在其他地方使用,那么实际值并不重要。
In general this only matters if the enum is exposed to some kind of external API or it is going to be used to exchange data via data files or other means. If the enum is only every used within your app and nowhere else then the actual values don't matter.