为什么在Delphi中可以自行分配? [英] Why is Self assignable in Delphi?

查看:209
本文介绍了为什么在Delphi中可以自行分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在GUI应用程序中的代码编译并运行:

This code in a GUI application compiles and runs:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Self := TForm1.Create(Owner);
end;

(用Delphi 6和2009测试)

(tested with Delphi 6 and 2009)


  • 为什么是自写而不是只读?

  • 在哪种情况下可以使用?

编辑:


  • 这是否也可能在Delphi Prism? (我想是的,请参阅 here

  • is this also possible in Delphi Prism? (I think yes it is, see here)

更新:
使用自我分配的Delphi应用程序/库:

Update: Delphi applications/libraries which make use of Self assignment:

  • python4delphi

推荐答案

这不是那么糟糕。我只是在Delphi 2009中进行了测试,似乎虽然Self参数不使用 const 语义,这似乎意味着它应该是,它也不使用 var 语义,因此您可以在方法中更改所有您想要的内容,而不会丢失调用者对您的对象的引用。这将是一件非常糟糕的事情。

That's not as bad as it could be. I just tested it in Delphi 2009, and it would seem that, while the Self parameter doesn't use const semantics, which you seem to be implying it should, it also doesn't use var semantics, so you can change it all you want within your method without actually losing the reference the caller holds to your object. That would be a very bad thing.

至于为什么,两个答案之一。要么是一个简单的监督,要么是Marco的建议:允许你将Self传递给 var 参数。

As for the reason why, one of two answers. Either a simple oversight, or what Marco suggested: to allow you to pass Self to a var parameter.

这篇关于为什么在Delphi中可以自行分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆