开发者

Howto set event handlers with arbitrary type with RTTI in Delphi 2010?

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.

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)

In old RTTI style I would do something like:

var
  开发者_StackOverflow中文版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;

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.

EDIT: Reported as QC# 81416. Vote it up if you want to see it fixed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜