作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用 Delphi 2009。我有一个包含多个项目的 TListBox。我想为每个选定的项目生成一个特定类的对象。因此,如果用户选择项目编号 2 并单击创建按钮,则会创建特定类的对象。我想实现它只是检查当前所选项目的索引值,然后使用 if-then-else。或者我应该使用类引用,即每次单击项目时,我都设置类引用的类型,然后在按钮的 OnClick 事件中创建对象?我想避免所有这些控件,只根据项目字符串的值创建对象。任何想法?非常感谢!
最佳答案
有几个选项。
简单索引
简单的解决方案是:
case ListBox1.ItemIndex of
0 : temp := TApple.Create;
1 : temp := TPineapple.Create;
2 : temp := TGrape.Create;
else
raise EFruitError.Create('Unknown fruit');
end;
很清楚,但是你必须在两个地方维护列表,这可能会导致错误。
类引用
假设所有水果都来自 TFruit,带有一个虚拟构造函数。然后你可以这样做:
procedure TForm1.FormCreate(const Sender: TObject);
begin
ListBox1.AddObject('Apple', TApple);
ListBox1.AddObject('Pineapple', TPineapple);
ListBox1.AddObject('Grape', TGrape);
end;
// Event handler:
procedure TForm1.CreateButtonClick(const Sender: TObject);
begin
if ListBox1.ItemIndex>=0 then
temp := TFruit(ListBox1.Items.Objects[ListBox1.ItemIndex]).Create;
end;
这有单点维护。这很棒。
基于名称的引用但是如果你想根据列表中的名称创建对象,你可以创建某种工厂:
type
TFruitClass = class of TFruit;
TFruitFactory = class
public
class function CreateFruit(const AName: string): TFruit;
class procedure RegisterFruit(const AName: string; const AFruitClass: TFruitClass);
end;
工厂用于将类绑定(bind)到名称。每个类都使用名称进行注册。现在您只需将名称提供给工厂,工厂就会返回所需的类。
关于DelphiWin32 - 生成特定类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4246471/
我是一名优秀的程序员,十分优秀!