解决方法
请注意,以下代码仅适用于已发布的类的属性!此外,传递给下面的函数的类的实例至少必须已经定义了发布的部分!
以下是使用旧样式RTTI将已发布的字符串属性值设置为空字符串,将布尔值设置为False.
如果您的Delphi比Delphi 2009更旧,您可能会丢失tkUString类型.如果是这样,请从以下代码中删除:
uses TypInfo; procedure ResetPropertyValues(const AObject: TObject); var PropIndex: Integer; PropCount: Integer; PropList: PPropList; PropInfo: PPropInfo; const TypeKinds: TTypeKinds = [tkEnumeration,tkString,tkLString,tkWString,tkUString]; begin PropCount := GetPropList(AObject.ClassInfo,TypeKinds,nil); GetMem(PropList,PropCount * SizeOf(PPropInfo)); try GetPropList(AObject.ClassInfo,PropList); for PropIndex := 0 to PropCount - 1 do begin PropInfo := PropList^[PropIndex]; if Assigned(PropInfo^.SetProc) then case PropInfo^.PropType^.Kind of tkString,tkUString,tkWString: SetStrProp(AObject,PropInfo,''); tkEnumeration: if GetTypeData(PropInfo^.PropType^)^.BaseType^ = TypeInfo(Boolean) then SetOrdProp(AObject,0); end; end; finally FreeMem(PropList); end; end;
这是一个简单的测试代码(注意属性必须发布;如果类中没有已发布的属性,至少空的发布部分必须在那里):
type TSampleClass = class(TObject) private FStringProp: string; FBooleanProp: Boolean; published property StringProp: string read FStringProp write FStringProp; property BooleanProp: Boolean read FBooleanProp write FBooleanProp; end; procedure TForm1.Button1Click(Sender: TObject); var SampleClass: TSampleClass; begin SampleClass := TSampleClass.Create; try SampleClass.StringProp := 'This must be cleared'; SampleClass.BooleanProp := True; ResetPropertyValues(SampleClass); ShowMessage('StringProp = ' + SampleClass.StringProp + sLineBreak + 'BooleanProp = ' + BoolToStr(SampleClass.BooleanProp)); finally SampleClass.Free; end; end;