如何在一个Delphi程序中同时使用Sender参数和As运算符处理多个类对象?

更新于
2026-10-04 22:34:01
2阅读来源:SEO教程
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计346个文字,预计阅读时间需要2分钟。

在Delphi中,有时我们需要这样编写函数:`function TForm1.EDIT_Click(Sender: TObject); begin (Sender As TEdit).Text :=''; end;` 但有时我们需要重复其他对象的类似功能,例如:`function TForm1.COMBOBOX_Click(Sender: TObject);`

在Delphi中,有时我们需要这样做……

function TForm1.EDIT_Click(Sender: TObject); begin (Sender As TEdit).Text := ''; end;

…但有时我们需要重复其他对象类的功能,如…

function TForm1.COMBOBOX_Click(Sender: TObject); begin (Sender As TComboBox).Text := ''; end;

…因为操作符As不接受灵活性.它必须知道该类才能允许()之后的.Text.

有时代码会充满类似的函数和过程,因为我们需要使用我们无法指定的类似可视控件来执行相同的操作.

这只是一个使用示例.通常,我在更复杂的代码上使用这些代码来实现许多控件和其他类型对象的标准目标.

是否有替代或技巧使这些任务更灵活?

使用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;

在某些情况下,某些控件使用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;

本文共计346个文字,预计阅读时间需要2分钟。

在Delphi中,有时我们需要这样编写函数:`function TForm1.EDIT_Click(Sender: TObject); begin (Sender As TEdit).Text :=''; end;` 但有时我们需要重复其他对象的类似功能,例如:`function TForm1.COMBOBOX_Click(Sender: TObject);`

在Delphi中,有时我们需要这样做……

function TForm1.EDIT_Click(Sender: TObject); begin (Sender As TEdit).Text := ''; end;

…但有时我们需要重复其他对象类的功能,如…

function TForm1.COMBOBOX_Click(Sender: TObject); begin (Sender As TComboBox).Text := ''; end;

…因为操作符As不接受灵活性.它必须知道该类才能允许()之后的.Text.

有时代码会充满类似的函数和过程,因为我们需要使用我们无法指定的类似可视控件来执行相同的操作.

这只是一个使用示例.通常,我在更复杂的代码上使用这些代码来实现许多控件和其他类型对象的标准目标.

是否有替代或技巧使这些任务更灵活?

使用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;

在某些情况下,某些控件使用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;