当其类型在另一个单元中间接定义时,如何使用枚举值?

kab*_*rgo 1 delphi enums scope

我正在努力减少数量Uses并遇到问题Enums

(* original unit, where types are defined etc *)
unit unit1;
type
  TSomeEnumType = (setValue1, setValue2, ...);
...
Run Code Online (Sandbox Code Playgroud)

(* global unit where all types are linked *)
unit unit2;
uses unit1;
type
  TSomeEnumType = unit1.TSomeEnumType;
...
Run Code Online (Sandbox Code Playgroud)

(* form unit that will use the global unit *)
unit unitform;
uses unit2;
...
procedure FormCreate(Sender : TObject);
var ATypeTest : TSomeEnumType;
begin
  ATypeTest := setValue1; (* error says undeclared *)
  ATypeTest := TSomeEnumType(0); (* Works but there's not point in use enum *)
end;
...
Run Code Online (Sandbox Code Playgroud)

问题是在单位形式中setValue1说它是未声明的.我怎么能绕过这个?

小智 5

您不仅可以导入类型,还可以导入常量,如下所示:

unit unit1;
type
  TSomeEnumType = (setValue1, setValue2, ...);
...
Run Code Online (Sandbox Code Playgroud)

/* global unit where all types are linked */
unit unit2;
uses unit1;
type
  TSomeEnumType = unit1.TSomeEnumType;
const
  setValue1 = unit1.setValue1;
  setValue2 = unit1.setValue2;
  ...
Run Code Online (Sandbox Code Playgroud)

需要注意的是,如果这个想法是,最终,各单位要使用unit2,从来没有unit1,但要允许当前使用单位unit1继续汇编,处理与另一种方法是删除unit1,把TSomeEnumTypeunit2直接,在你的项目选项,放入unit1=unit2单位别名.每当一个单位出现时uses unit1;,它就会真正进入unit2.