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

℡╲_俬逩灬. 提交于 2019-12-05 04:02:21

问题


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
  NilMethod: TMethod;
begin
[...]
NilMethod.Data := nil;
NilMethod.Code := nil;
SetMethodProp (AComponent,PropertyName,NilMethod);

回答1:


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.



来源:https://stackoverflow.com/questions/2116013/howto-set-event-handlers-with-arbitrary-type-with-rtti-in-delphi-2010

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!