我想枚舉所有屬性:私人,保護,公共等我希望使用內置的設施,不使用任何第三方代碼。如何枚舉對象中的所有屬性並獲取其值?
6
A
回答
5
使用擴展RTTI這樣的(當我測試了XE的代碼我得到異常的ComObject財產,所以我插入的嘗試 - 除了塊):
uses RTTI;
procedure TForm1.Button1Click(Sender: TObject);
var
C: TRttiContext;
T: TRttiType;
F: TRttiField;
P: TRttiProperty;
S: string;
begin
T:= C.GetType(TButton);
Memo1.Lines.Add('---- Fields -----');
for F in T.GetFields do begin
S:= F.ToString + ' : ' + F.GetValue(Button1).ToString;
Memo1.Lines.Add(S);
end;
Memo1.Lines.Add('---- Properties -----');
for P in T.GetProperties do begin
try
S:= P.ToString;
S:= S + ' : ' + P.GetValue(Button1).ToString;
Memo1.Lines.Add(S);
except
ShowMessage(S);
end;
end;
end;
7
SERG的回答是好,但最好避免
uses
Rtti, TypInfo;
procedure TForm4.GetObjectProperties(AObject: TObject; AList: TStrings);
var
ctx: TRttiContext;
rType: TRttiType;
rProp: TRttiProperty;
AValue: TValue;
sVal: string;
const
SKIP_PROP_TYPES = [tkUnknown, tkInterface];
begin
if not Assigned(AObject) and not Assigned(AList) then
Exit;
ctx := TRttiContext.Create;
rType := ctx.GetType(AObject.ClassInfo);
for rProp in rType.GetProperties do
begin
if (rProp.IsReadable) and not (rProp.PropertyType.TypeKind in SKIP_PROP_TYPES) then
begin
AValue := rProp.GetValue(AObject);
if AValue.IsEmpty then
begin
sVal := 'nil';
end
else
begin
if AValue.Kind in [tkUString, tkString, tkWString, tkChar, tkWChar] then
sVal := QuotedStr(AValue.ToString)
else
sVal := AValue.ToString;
end;
AList.Add(rProp.Name + '=' + sVal);
end;
end;
end;
2
下面是使用的最新版本的Delphi高級功能的最佳出發點:
-
通過跳過某些類型的異常
- Rtti Explorer Lite來自RRUZ。
下面的鏈接,而不是目標早期版本(從D5開始)。基於TypInfo.pas單位,它是有限的,但仍具有啓發性:
相關問題
- 1. 如何枚舉所有對象並獲取它們的屬性?
- 2. 獲取所有值的屬性對象
- 3. 如何枚舉JavaScript對象的屬性?
- 4. TestComplete對象 - 枚舉屬性
- 5. 獲取枚舉併發送枚舉值
- 6. 如何獲取c#中的值的枚舉屬性?
- 7. 如何獲取枚舉中屬性的值?
- 8. 枚舉Mozilla中的所有屬性JSAPI
- 9. 如何枚舉所有設備對象?
- 10. 如何獲取XMLBeans中的所有枚舉值?
- 11. 如何獲取枚舉值?
- 12. 如何獲取枚舉值;
- 13. 如何獲取枚舉的自定義屬性值?
- 14. Grails根據枚舉列表屬性中的枚舉值選擇域對象
- 15. 列表對象屬性的枚舉器
- 16. 枚舉PowerShell對象的屬性拋出
- 17. 如何在C#中通過值獲取枚舉對象?
- 18. 選擇枚舉值枚舉屬性
- 19. 枚舉ViewData.Model的所有屬性
- 20. 如何獲得枚舉的屬性
- 21. 如何獲取此對象中文本的所有屬性?
- 22. 如何在C中獲取對象的所有簡單屬性#
- 23. 如何在PHP中獲取類的所有非對象屬性?
- 24. simplexml獲取值並非所有屬性
- 25. 如何通過反射獲取枚舉值的所有描述?
- 26. 枚舉通過對象屬性
- 27. 如何獲取枚舉值的值?
- 28. 使用以g枚舉值:選擇當枚舉是選擇對象的屬性
- 29. MATLAB - 獲取屬性所屬的對象?
- 30. Visualstudio宏 - 枚舉所有項目屬性
您正在使用哪個版本的Delphi?增強RTTI僅在德爾福2010年以後纔可用。舊版本將無法實現此目的:只能列出發佈的屬性。 – 2011-12-30 13:10:32
您正在詢問獲取所有房產的價值。 Delphi XE2提供的新RTTI可以做到這一點。我發佈的重複鏈接是關於使用RTTI的一些參考資料。沒有跡象表明你正在使用的Delphi版本。既然你編輯了你的問題,我刪除了我的副本。 – 2011-12-30 13:57:31
@DavidHeffernan,謝謝你很好地修改我的問題。 – VibeeshanRC 2011-12-30 14:06:50