2012-02-03 39 views
3

我正在創建一個類似於對象檢查器的控件,所以我想將屬性的任何更改分配給相關對象。在Delphi中動態分配值

var 

v:TValue ; 
ctx : TRttiContext; 
begin 

    // k.IsOrdinal := true ; 
v := v.FromVariant(2) ; 


ctx.GetType(tButton).GetProperty('Style').SetValue(Button1, v.AsOrdinal); 

end; 

上面是我的代碼,但我越來越無效類型轉換錯誤。

是否可以處理任何變量和枚舉(無需對象和記錄的,因爲它是很複雜)

回答

5

給setValue的調用需要這樣寫:

SetValue(Button1, TValue.From(TButton.TButtonStyle(2))) 

在你代碼,使用AsOrdinal是不正確的。這是一個返回TRttiOrdinalType的函數。但是TRttiOrdinalTypedescribed thus

TRttiOrdinalType is the class used to describe all the Delphi ordinal value types, such as Integer, Byte, Word, and so on.

但是,你需要提供一個TValue代表一個TButtonStyle,這是上面的代碼實現。


順便說一句,我最初嘗試使用通用TValue.From<T>()功能是這樣的:

SetValue(Button1, TValue.From<TButton.TButtonStyle>(TButton.TButtonStyle(2))); 

但是,這只是取得了以下內部編譯器錯誤:

[DCC Fatal Error] Unit58.pas(38): F2084 Internal Error: URW1147

QC#103129

每次我嘗試使用通用我最終被這些內部錯誤所擊敗!

感謝Serg指出使用類型推斷調用parameterised method的替代形式並不違背內部錯誤。

+0

謝謝,這就是我需要的 – VibeeshanRC 2012-02-03 12:43:04

+0

我想你在這裏濫用泛型;嘗試只是'SetValue(Button1,TValue.From(TButton.TButtonStyle(2)));' – kludg 2012-02-03 13:13:54

+0

@Serg你是正確的,你給的表單,它使用類型推斷,不會導致內部錯誤。但我並不濫用泛型。我使用的語法是完全有效的:http://docwiki.embarcadero.com/RADStudio/en/Declaring_Generics#Parameterized_Methods – 2012-02-03 13:26:02