- Delphi Cookbook
- Daniele Spinetti Daniele Teti
- 185字
- 2025-04-04 16:22:47
There's more...
Duck typing is a very broad topic and allows you to do wonderful things with a few lines of code. In this recipe's code, there is a bonus recipe project called DuckTypingUsingRTTIExtended.dproj, which contains an advanced version of the base recipe. It uses a fluent interface, allows you to select the components that you want to change, and defines what type of change to make on those components; something similar to the following code snippets. Set all the Caption properties of the components on the form to On All Captions:
Duck(Self).All.SetProperty('Caption').ToValue('On All Captions');
Set all the Text properties to 'Hello There' for the components with a name starting with 'Edit', using an anonymous method as a filter to select the components:
Duck(Self) .Where(function(C: TComponent): boolean begin Result := String(C.Name).StartsWith('Edit'); end) .SetProperty('Text') .ToValue('Hello There');
Set the Color property to clRed for all the TEdit components on the form. Use an anonymous method to define what to do on the components:
Duck(Self).Where(TEdit).Apply( procedure(C: TComponent) begin TEdit(C).Color := clRed; end);
In the bonus recipe, there are more examples. Feel free to experiment and expand on them.