为什么我得到“类型没有类型信息"?枚举类型错误 [英] Why do I get "type has no typeinfo" error with an enum type

查看:28
本文介绍了为什么我得到“类型没有类型信息"?枚举类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了以下枚举类型,我希望第一个成员的序号值为 1(一)而不是通常的 0(零):

I have declared the following enum type in which I want the first member to have the ordinal value of 1 (one) rather than the usual 0 (zero):

  type
    TMyEnum = (
               meFirstValue = 1,
               meSecondValue,
               meThirdValue
              );

如果我调用 TypeInfo(),例如作为对 GetEnumName() 调用的一部分,我收到一个编译器错误:

If I call TypeInfo(), e.g. as part of a call to GetEnumName(), I get a compiler error:

  GetEnumName(TypeInfo(TMyEnum), Ord(aValue));

错误:E2134:类型‘TMyEnum’没有类型信息"

这是为什么?

我知道类只有在启用 $M 编译器选项的情况下编译时才具有 typeinfo 或(源自某个类,例如 TPersistent)但我不认为枚举类型有 typeinfo 有什么特殊条件.

I know that classes only have typeinfo if they are compiled with the $M compiler option enabled or (derive from some class which was, such as TPersistent) but I didn't think there were any special conditions for having typeinfo for enum types.

推荐答案

枚举不支持类型信息,其中分配了特定序数值,导致枚举成员的序数值与通常由编译器.

Type information is not supported for enums where specific ordinal values are assigned that result in enum members having ordinal values that are different to those that would normally be assigned by the compiler.

如果特定值是必不可少的或需要的,则必须根据需要插入未使用"的枚举成员以填充"枚举.例如(仅用于强调的额外缩进):

If specific values are essential or desirable, "unused" enum members will have to be inserted to "pad" the enum as required. e.g (additional indentation for emphasis only):

  type
    TMyEnum = (
                meNOTUSED1,   {= 0}
               meFirstValue,  {= 1} 
               meSecondValue,
               meThirdValue
              );

然后可以使用子范围来过滤"掉未使用的初始值:

A subrange can then be used to "filter" out the unused initial value:

   TValidMyEnum = meFirstValue..meThirdValue;

尽管您可能希望考虑重命名原始枚举类型,以便您的子范围类型可以在整个项目中使用.

Although you might then wish to consider renaming the original enum type so that your subrange type may be used throughout your project.

如果枚举包含间隙",则子范围是不够的:

A subrange isn't sufficient if the enum contains "gaps":

  type
    TMyEnum = (
                meNOTUSED1,   {= 0}
               meFirstValue,  {= 1} 
               meSecondValue,
               meThirdValue,
                meNOTUSED2,
               meFinalValue   {= 5}
              );

在这种情况下,没有简单的方法来扩展编译时范围检查以排除未使用的成员,但有几个集合类型将简化实现任何必要的运行时检查的业务:>

In this case there is no simply way to extend compile-time range checking to exclude the unused members, but a couple of set types will simplify the business of implementing any necessary runtime checks:

  type
    TMyEnums = set of TMyEnum;

  const
    meNOTUSED      = [meUNUSED1, meUNUSED2]; //  .. etc as required
    meValidValues  = [Low(TMyEnum)..High(TMyEnum)] - meNOTUSED;


  if NOT (aValue in meValidValues) then
     // etc

这篇关于为什么我得到“类型没有类型信息"?枚举类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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