2011-05-15 42 views
3

檢查這個簡化的示例(真實場景是不同的),我想設置一個對象的嵌套屬性的值,在這種情況下設置顏色的使用RTTI將TLabel組件的字體改爲clRed我如何設置使用RTTI的嵌套屬性的值

var 
    p : TRttiProperty; 
    p2: TRttiProperty; 
    c : TRttiContext; 
begin 
    c := TRttiContext.Create; 
    try 
    p := c.GetType(Label1.ClassInfo).GetProperty('Font'); 
    p2 := c.GetType(p.PropertyType.Handle).GetProperty('Color'); 
    p2.SetValue(p.PropertyType.AsInstance,clred); //this line is not working 
    finally 
    c.Free; 
    end; 
end; 

還我試圖

p2.SetValue(Label1,clred); 

回答

3

下面的代碼將正常工作。

var 
    p : TRttiProperty; 
    p2: TRttiProperty; 
    c : TRttiContext; 
begin 
    c := TRttiContext.Create; 
    try 
    p := c.GetType(Label1.ClassInfo).GetProperty('Font'); 
    p2 := c.GetType(p.PropertyType.Handle).GetProperty('Color'); 
    p2.SetValue(p.GetValue(Label1).AsObject,clred); //this line now works. 
    finally 
    c.Free; 
    end; 
end; 

您需要從標籤中獲取嵌入字體。 TRttiProperty處理類型而不處理實例。您需要撥打GetValue()SetValue()來處理該實例。

您的原始代碼引用的是類型而不是實例。

+0

非常感謝,羅伯特。 – Salvador 2011-05-15 19:21:57

相關問題