Ple*_*rds 4 delphi oop sender as-operator
在Delphi中,有时我们需要这样做......
function TForm1.EDIT_Click(Sender: TObject);
begin
(Sender As TEdit).Text := '';
end;
Run Code Online (Sandbox Code Playgroud)
...但有时我们需要重复其他对象类的功能,如...
function TForm1.COMBOBOX_Click(Sender: TObject);
begin
(Sender As TComboBox).Text := '';
end;
Run Code Online (Sandbox Code Playgroud)
......因为运营商As
不接受灵活性.它必须知道这个类,以便允许.Text
它来之后()
.
有时候代码会变得类似functions
,procedures
因为我们需要使用类似的视觉控件来做同样的事情,而这些控件是我们无法指定的.
这只是一个使用示例.通常,我在更复杂的代码上使用这些代码来实现许多控件和其他类型对象的标准目标.
是否有替代或技巧使这些任务更灵活?
Rem*_*eau 11
使用RTTI在不相关类的类似命名属性上执行常见任务,例如:
Uses
..., TypInfo;
// Assigned to both TEdit and TComboBox
function TForm1.ControlClick(Sender: TObject);
var
PropInfo: PPropInfo;
begin
PropInfo := GetPropInfo(Sender, 'Text', []);
if Assigned(PropInfo) then
SetStrProp(Sender, PropInfo, '');
end;
Run Code Online (Sandbox Code Playgroud)
在某些情况下,一些控件使用Text
而一些使用Caption
,例如;
function TForm1.ControlClick(Sender: TObject);
var
PropInfo: PPropInfo;
begin
PropInfo := GetPropInfo(Sender, 'Text', []);
if not Assigned(PropInfo) then
PropInfo := GetPropInfo(Sender, 'Caption', []);
if Assigned(PropInfo) then
SetStrProp(Sender, PropInfo, '');
end;
Run Code Online (Sandbox Code Playgroud)
你可以使用is
运算符,试试这个样本
if Sender is TEdit then
TEdit(Sender).Text:=''
else
if Sender is TComboBox then
TComboBox(Sender).Text:='';
Run Code Online (Sandbox Code Playgroud)
您可以使用absolute关键字来消除混乱的类型转换,该关键字允许您声明占用相同内存位置的不同类型的变量,在这种情况下与事件参数位于相同的位置.
您仍然需要使用"is"执行类型检查,但在其他方面,这种方法更清洁但同样安全.
procedure TMyForm.ControlClick(Sender: TObject);
var
edit: TEdit absolute Sender;
combo: TComboBox absolute Sender;
:
begin
if Sender is TEdit then
edit.Text := ''
else if Sender is TComboBox then
combobox.Text := ''
else
:
end;
Run Code Online (Sandbox Code Playgroud)
我在 3年前的博客中更详细地写了关于使用这种语言功能的文章.