在Delphi 2010中如何使用RTTI设置任意类型的事件处理程序? [英] Howto set event handlers with arbitrary type with RTTI in Delphi 2010?
问题描述
阅读发布后的如何通过新的设置事件处理程序RTTI?,我想知道是否可以更加动态地解决这个问题。例如,我想将任何组件的所有事件处理程序设置为nil。
after reading the post How to set event handlers via new RTTI?, I wonder if it is possible to solve this more dynamically. For example I want to set ALL event handlers of any component to nil.
使用 TValue.From< TNotifyEvent> (SomeMethod)
不起作用有两个原因:
1.类型是未知的(可能是TNotifyEvent,TMouseEvent等)
2.我无法将SomeMethod设置为nil (无效转换)
Using TValue.From <TNotifyEvent> (SomeMethod)
does not work for two reasons:
1. The type is unknown (could be TNotifyEvent, TMouseEvent etc.)
2. I cannot set 'SomeMethod' to nil (invalid cast)
在旧的RTTI样式中,我将执行以下操作:
In old RTTI style I would do something like:
var
NilMethod: TMethod;
begin
[...]
NilMethod.Data := nil;
NilMethod.Code := nil;
SetMethodProp (AComponent,PropertyName,NilMethod);
推荐答案
以下代码应该可以正常工作:
The following code ought to work:
procedure NilAllEventHandlers(myObject: TObject);
var
context: TRttiContext;
rType: TRttiType;
field: TRttiField;
value: TValue;
nilMethod: TMethod;
begin
nilMethod.Code := nil;
nilMethod.Data := nil;
context := TRttiContext.Create;
rType := context.GetType(TButton);
for field in rType.GetFields do
begin
if field.FieldType.TypeKind = tkMethod then
begin
TValue.Make(@nilMethod, field.FieldType.Handle, value);
field.SetValue(myObject, value);
end;
end;
end;
但它并不是因为在使用TMethod值时,TValue.TryCast中有一个错误。代码参数为 nil 。我会报告给QC。希望它将在D2011或更新中得到修复。在此之前,尝试旧样式。
But it doesn't because there's a bug in TValue.TryCast when working with a TMethod value whose .Code parameter is nil. I'll report it to QC. Hopefully it'll get fixed in D2011 or an update. Until then, try the old style.
编辑:报告为 QC#81416 。如果你想看到它固定,请投票。
Reported as QC# 81416. Vote it up if you want to see it fixed.
这篇关于在Delphi 2010中如何使用RTTI设置任意类型的事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!