Author: Jonas Bilinkevicius
The piece of code below is typical of some routines we have. This example only uses
2 component types but sometimes there could be 7 or 8 and then the code is really
bad.
1 procedure TEN1FORM.myonEnter(Sender: TObject);
2 begin3 if Sender is TDBComboBox then4 enterstr := TDBComboBox(Sender).text
5 elseif Sender is TOVCDBPICTUREFIELD then6 enterstr := TOVCdbPICTUREFIELD(Sender).text;
7 end;
Answer:
Solve 1:
8 function CheckIsType(AObject: TObject; const ClassArray: arrayof TClass):
9 Integer;
10 {Return an index indicative of a type match on the object, and array of types 11 passed}12 begin13 for Result := 0 to High(ClassArray) do14 if AObject is ClassArray[Result] then15 Exit;
16 Result := -1;
17 end;
18 19 { ... }20 case CheckIsType(Sender, [TdbComboBox, TOVCDBPctureField, TSpeedButton, TEdit]) of21 0: { ... }; {TDBComboBox}22 1: { ... }; {TOVCDBPctureField}23 2: { ... }; {TSpeedButton}24 3: { ... }; {TEdit}25 end;
26 { ... }
I also use the following routine which does an exact type match:
27 function CheckType(AObject: TObject; const ClassArray: arrayof TClass):
28 Integer;
29 var30 Index: Integer;
31 begin32 Result := -1;
33 if Assigned(AObject) then34 for Index := 0 to High(ClassArray) do35 if AObject.ClassType = ClassArray[Index] then36 begin37 Result := Index;
38 Exit;
39 end;
40 end;
Solve 2:
Let me add one more way to tackle this: use run-time type information. Text is a
published property so RTTI exists for it. So you can use the stuff in Unit TypInfo
to access it.
41 uses42 TypInfo;
43 44 function GetStrProperty(anObj: TObject; const propname: string): string;
45 var46 PInfo: PPropInfo;
47 begin48 result := EmptyStr;
49 PInfo := GetPropInfo(anObj.ClassInfo, propname);
50 if PInfo <> nilthen51 {found aproperty with this name, check if it has the correct type}52 if PInfo^.Proptype^.Kind in [tkString, tkLString] then53 begin54 {it has! Get the string value from theproperty}55 Result := GetStrProp(anObj, PInfo);
56 end;
57 end;
58 59 Using this function your handler becomes
60 61 procedure TEN1FORM.myonEnter(Sender: TObject);
62 begin63 enterstr := GetStrProperty(sender, 'text');
64 { ... }