How to make collective operations in a set of data perceived controls

zhaozj2021-02-16  52

Many times you need to set the readOrthly of all the data perceived controls in the interface to True or False, what do you do?

The earliest time I this way: enumerate each type, if there are more, the code will be a lot

for i: = 0 to ComponentCount - 1 do begin if Components [i] is TDBMemo then begin TDBMemo (Components [i]) ReadOnly: = true; continue; end; if Components [i] is TDBRadioGroup then begin TDBRadioGroup (Components [. I]). Readonly: = true; Continue; End; if Components [i] is tdbedit dam tdbedit (Components [i]). Readonly: = true; Continue; End; ........... ...........

I then, because the data perceived control has a DataSource and DataField properties, so use the RTTI information to set

for i: = 0 to ComponentCount - 1 do begin if IsPublishedProp (Components [i], 'DataSource') and IsPublishedProp (Components [i], 'DataField') then SetVariantProp (Components [i], 'ReadOnly', true);

I think this is already the shortest code under Delphi, don't forget to join the Typinfo unit.

Thus, if all the data perceived controls implement iDataControl (name) interface, we are determined by TOBJECT.IMplementorof to determine if it is a data-sensing control, so it is very specific, And you can reduce a line of code. So when you operate a common class, you don't have to enumerate each class to prevent compilation errors (such as the first method), nor do you use your experience to define their commonality (eg The second method). I even paranoid think that the public method and publication attributes of each class should be in the definition of an interface. After all, you can't guarantee that it is unique, there may be other similar classes. And assign At the time, just need to be as an interface, the code may be the following

For i: = 0 to ComponentCount - 1 Do Begin if Components [i] .Isimplementorof (iDatacontrol) (Components [i] as iDataControl) .readOnly: = true;

转载请注明原文地址:https://www.9cbs.com/read-21436.html

New Post(0)