Author: Jonas Bilinkevicius
In my application, the user has a form where he is selecting from a list of
options. That list of options corresponds to contant values. Is there a way to find
the value of a constant when all you have is a string containing its name?
Example:
1 const2 TEST = 5;
3 DELIVERED = 10
4 { ... }5 6 sChoice := listboxChoice.Text // -possible values are TEST and DELIVERED7 iChoice = {missing method}(sChoice)
iChoice would be assigned the value of the constant of the same name as the user's
selection. No, I can't change the declarations to be enumerated types or anything
else. They have to be constants. I've seen examples of this sort of thing done for
Enumerated types, objects and so on using RTTI. But I can't find an example of
constants, and I can't figure it out.
Answer:
Solve 1:
If enumerations are okay (I don't see how you could use names of constants), try
this to get mapping of enumeration from string to integer:
8 { ... }9 type10 TConstValues = (cvTest, cvDelivered);
11 12 var13 values = array[TConstValues] of integer = (5, 10);
14 strings = array[TConstValues] ofstring = ('TEST', 'DELIVERED');
15 16 { ... }17 18 function GetConstValue(s: string): integer;
19 var20 t: TConstValues;
21 begin22 result := -1;
23 for t := low(TConstValues) to high(TConstvalues) do24 if strings[t] = s then25 begin26 result := values[t];
27 break;
28 end;
29 end;
Solve 2:
This is a modification of Solve 1:
30 { ... }31 const32 TCVals: array[TConstValues] of integer = (-1, 5, 10);
33 TCStrs: array[TConstValues] ofstring = ('UNKNOWN', 'TEST', 'DELIVERED');
34 { ... }35 36 function GetConstValue(s: string): integer;
37 var38 t: TConstValues;
39 begin40 t := high(TConstvalues);
41 while (t > low(TConstValues)) and (CompareText(TCStrs[t], s) <> 0) do42 dec(t);
43 Result := TCVals[t];
44 end;