How do I use enum values when their type is defined indirectly in another unit?

我如何使用枚举值间接当他们的类型是定义在另一个单位?

问题 (Question)

I am trying to reduce the number of Uses and am running into problems with Enums

(* original unit, where types are defined etc *)
unit unit1;
type
  TSomeEnumType = (setValue1, setValue2, ...);
...

(* global unit where all types are linked *)
unit unit2;
uses unit1;
type
  TSomeEnumType = unit1.TSomeEnumType;
...

(* 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;
...

The problem is that in the unitform setValue1 says it is undeclared. How can I get around this?

我试图减少的数量Uses和我遇到的问题Enums

(* original unit, where types are defined etc *)
unit unit1;
type
  TSomeEnumType = (setValue1, setValue2, ...);
...

(* global unit where all types are linked *)
unit unit2;
uses unit1;
type
  TSomeEnumType = unit1.TSomeEnumType;
...

(* 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;
...

问题是,在unitformsetValue1说它是未申报。我怎样才能解决这个问题?

最佳答案 (Best Answer)

You can not only import the type, but also the constants, like so:

unit unit1;
type
  TSomeEnumType = (setValue1, setValue2, ...);
...

/* global unit where all types are linked */
unit unit2;
uses unit1;
type
  TSomeEnumType = unit1.TSomeEnumType;
const
  setValue1 = unit1.setValue1;
  setValue2 = unit1.setValue2;
  ...

Note that if the idea is that in the end, all units should use unit2 and never unit1, but you want to allow units that currently use unit1 to continue compiling, another way of dealing with that is to remove unit1, put TSomeEnumType in unit2 directly, and in your project options, put unit1=unit2 in the unit aliases. Every time a unit then does uses unit1;, it will really pull in unit2.

你不仅可以导入类型,常量,像这样:

unit unit1;

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/16925937