我怎样才能使我的代码工作?:)我试图制定这个问题,但经过几次失败的尝试后,我认为你们会更快地发现问题,而不是阅读我的"解释".谢谢.
setCtrlState([ memo1, edit1, button1], False);
Run Code Online (Sandbox Code Playgroud)
_
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;
Run Code Online (Sandbox Code Playgroud)
您必须显式地将对象强制转换为某个类.这应该工作:
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;
Run Code Online (Sandbox Code Playgroud)
这可以使用" 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;
Run Code Online (Sandbox Code Playgroud)
使用RTTI而不是显式转换会更容易,即:
uses
TypInfo;
setCtrlState([ memo1, edit1, button1], False);
procedure setCtrlState(objs: array of TObject; bState: boolean = True);
var
obj: TObject;
PropInfo: PPropInfo;
begin
for obj in objs do
begin
PropInfo := GetPropInfo(obj, 'ReadOnly');
if PropInfo <> nil then SetOrdProp(obj, PropInfo, not bState);
PropInfo := GetPropInfo(obj, 'Enabled');
if PropInfo <> nil then SetOrdProp(obj, PropInfo, bState);
end;
end;
Run Code Online (Sandbox Code Playgroud)