从 Type1 获取的 Rtti 方法可以在 Type2 的对象上调用
我有以下程序。
procedure TForm1.Button1Click(Sender: TObject);
begin
var con: TRttiContext;
var meth := con.GetType(TButton).GetMethod('Click');
meth.Invoke(BitBtn1, []);
end;
BitBtn1
是一个 TBitBtn。如您所见,meth
是从类型 TButton
获取的方法对象。但是,根据我的测试,可以针对 TBitBtn 调用它,没有任何问题。这是预期的吗?
I have the following program.
procedure TForm1.Button1Click(Sender: TObject);
begin
var con: TRttiContext;
var meth := con.GetType(TButton).GetMethod('Click');
meth.Invoke(BitBtn1, []);
end;
BitBtn1
is a TBitBtn. As you can see, meth
is a method object got from type TButton
. But, by my testing, it can be invoked against a TBitBtn without any issue. Is this expected?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您发布的 RTTI 之所以有效,是因为
TBitBtn
和TButton
共享一个共同的祖先 (TCustomButton
),它实现了Click
> 方法。如果您使用的两种类型并非源自实现相同方法的祖先,例如
TEdit
和TMemo
,则代码将会失败。两者都允许您输入文本,但TMemo
具有属性Lines
。TEdit
不会,这会导致您发布的代码失败。The RTTI you've posted works because both
TBitBtn
andTButton
share a common ancestor (TCustomButton
) which implements theClick
method.The code would fail if you used two types that didn't descend from an ancestor that implemented the same method, such as
TEdit
andTMemo
. Both allow you to enter text, butTMemo
has the propertyLines
.TEdit
does not, which would cause the code you've posted to fail.