如何限制目标C中枚举值的可见性? [英] How to limit visibility of enum values in Objective C?

查看:166
本文介绍了如何限制目标C中枚举值的可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在目标C中,在定义枚举时,所有枚举值都可以随处可见,并阻止全局命名空间。



我想让它成为Java-风格和强制枚举只能通过枚举类型名称访问,例如与

  typedef枚举
{
MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FREDAY,SATURDAY,SUNDAY, NUM_OF
}天;

我想确保
只需调用 MONDAY 产生编译错误或至少是警告,访问枚举值的唯一方法是像$ code> Day.MONDAY Day: :MONDAY [Day MONDAY] 或...



在Java中,我或者使用枚举或接口,但是这在Objective-C中是可行的吗?



如果没有,那么我必须命名所有的枚举,如下所示: DAY_MONDAY,DAY_TUESDAY ... ,以便在自动完成弹出窗口中轻松浏览。

解决方案

p>这只是一个解决方法,但是您可以使用多个类方法创建一个自定义界面(因此不需要创建一个实例),每个方法都代表一个常量。



这种方式的常量只有在你问的时候才可以访问(即 Day.MONDAY [日MONDAY] )。


In Objective C, when you define an enum, all of the enum values are visible everywhere and clog the global namespace.

I would like to make it Java-style and enforce that enums are only accessible thru the enum type name, e.g. with

typedef enum
{
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY, NUM_OF
} Day;

I want to make sure that simply calling MONDAY produces compilation error or at least warning, and the only way to access the enum value were something like Day.MONDAY or Day::MONDAY or [Day MONDAY] or...

In Java I either use Enums or Interfaces, but is this doable in Objective-C?

If not, then I'd have to name all enums like this: DAY_MONDAY, DAY_TUESDAY... to make them easier to seach in auto-completion pop-up.

解决方案

It's just a workaround, but you can create a custom interface with a number of class methods (so that there's no need to create an instance), where each method represent a constant.

This way constants will be accessible only as you asked (ie. Day.MONDAY or [Day MONDAY]).

这篇关于如何限制目标C中枚举值的可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆