Tre*_*tBG 4 delphi types class delphi-7
我有几个不同的类,它们是另一个类.我有一个属性扩展到所有其他类.但不同的类处理此属性的方式不同.所以我想这样做:
TClass(ObjectPointer).Property:=值;
但是TClass是未知的类型
我可以这样做吗:
ObjectPointer.ClassType(ObjectPointer).Property:=值
或这个
var
ClassRef: TClass;
begin
ClassRef := Sender.ClassType;
ClassRef(ObjectPointer).DoStuff
end;
Run Code Online (Sandbox Code Playgroud)
有没有办法在delphi中执行此操作而不使用if语句
请注意,此帖子中的代码仅适用于已发布的媒体资源!
要回答您的问题,如果有办法在不使用if语句的情况下设置属性值,请检查以下重载函数.
第一个是char,string,variant,integer,64位整数,float,枚举,set和动态数组类型的属性(phew).第二个是仅用于类类型属性.如果存在给定属性并且成功分配了值或对象实例,则两者都将返回True,否则返回False:
uses
TypInfo;
function TrySetPropValue(AInstance: TObject; const APropName: string;
const AValue: Variant): Boolean; overload;
begin
Result := True;
try
SetPropValue(AInstance, APropName, AValue);
except
Result := False;
end;
end;
function TrySetPropValue(AInstance: TObject; const APropName: string;
AValue: TObject): Boolean; overload;
begin
Result := True;
try
SetObjectProp(AInstance, APropName, AValue);
except
Result := False;
end;
end;
Run Code Online (Sandbox Code Playgroud)
和用法; 当Memo1.Lines设置为时,第二个版本TrySetPropValue被称为:
procedure TForm1.Button1Click(Sender: TObject);
var
Strings: TStringList;
begin
TrySetPropValue(Memo1, 'Width', 250);
TrySetPropValue(Memo1, 'Height', 100);
TrySetPropValue(Memo1, 'ScrollBars', ssBoth);
Strings := TStringList.Create;
try
Strings.Add('First line');
Strings.Add('Second line');
TrySetPropValue(Memo1, 'Lines', Strings);
finally
Strings.Free;
end;
if not TrySetPropValue(Memo1, 'Height', 'String') then
ShowMessage('Property doesn''t exist or the value is invalid...');
if not TrySetPropValue(Memo1, 'Nonsense', 123456) then
ShowMessage('Property doesn''t exist or the value is invalid...');
end;
Run Code Online (Sandbox Code Playgroud)