gpt4 book ai didi

delphi - 使用他的 ClassType 来转换 TObject?

转载 作者:行者123 更新时间:2023-12-03 15:03:24 39 4
gpt4 key购买 nike

我怎样才能让我的代码工作? :) 我试图提出这个问题,但经过几次失败的尝试后,我认为你们通过查看代码会比阅读我的“解释”更快地发现问题。谢谢。

setCtrlState([ memo1, edit1, button1], False);

_

procedure setCtrlState(objs: array of TObject; bState: boolean = True);
var
obj: TObject;
ct: TClass;
begin
for obj in objs do
begin
ct := obj.ClassType;


if (ct = TMemo) or (ct = TEdit) then
ct( obj ).ReadOnly := not bState; // error here :(

if ct = TButton then
ct( obj ).Enabled:= bState; // and here :(

end;
end;

最佳答案

您必须将对象显式转换为某个类。这应该有效:

 procedure setCtrlState(objs: array of TObject; bState: boolean = True);
var
obj: TObject;
ct: TClass;
begin
for obj in objs do
begin
ct := obj.ClassType;

if ct = TMemo then
TMemo(obj).ReadOnly := not bState
else if ct = TEdit then
TEdit(obj).ReadOnly := not bState
else if ct = TButton then
TButton(obj).Enabled := bState;
end;
end;

这可以使用“is”运算符来缩短 - 不需要 ct 变量:

 procedure setCtrlState(objs: array of TObject; bState: boolean = True);
var
obj: TObject;
begin
for obj in objs do
begin
if obj is TMemo then
TMemo(obj).ReadOnly := not bState
else if obj is TEdit then
TEdit(obj).ReadOnly := not bState
else if obj is TButton then
TButton(obj).Enabled := bState;
end;
end;

关于delphi - 使用他的 ClassType 来转换 TObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1083087/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com