我怎么才能让我的代码工作呢?:)我已经尝试过这个问题,但在几次失败的尝试之后,我想你们看代码会比看我的“解释”更快地发现问题。谢谢。
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;
发布于 2009-07-07 17:02:15
使用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;
发布于 2009-07-04 14:59:46
您必须将对象显式强制转换为某个类。这应该是可行的:
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;
发布于 2009-07-04 14:38:52
您需要将ct对象强制转换为TMemo/TEdit/TButton,然后才能设置该对象的属性。
出现错误的代码行是错误的,因为ct仍然是一个TClass,而不是TButton/等。如果您强制转换为TButton,那么您将能够将enabled设置为true。
我推荐阅读casting in Delphi上的内容。就我个人而言,我建议使用as/is运算符,而不是使用ClassType。在这种情况下,代码会更简单,也更容易理解。
就我个人而言,我更倾向于这样写:
procedure setCtrlState(objs: array of TObject; bState: boolean = True);
var
obj: TObject;
begin
for obj in objs do
begin
// I believe these could be merged by using an ancestor of TMemo+TEdit (TControl?)
// but I don't have a good delphi reference handy
if (obj is TMemo) then
TMemo(obj).ReadOnly := not bState;
if (obj is TEdit) then
TEdit(obj).ReadOnly := not bState;
if (obj is TButton) then
TButton(obj).Enabled := bState;
end;
end;
https://stackoverflow.com/questions/1083087
复制相似问题