为什么我不应该使用“with"?在德尔福? [英] Why should I not use "with" in Delphi?

查看:39
本文介绍了为什么我不应该使用“with"?在德尔福?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说很多程序员,尤其是 Delphi 程序员鄙视with"的使用.

I've heard many programmers, particularly Delphi programmers scorn the use of 'with'.

我认为它使程序运行得更快(只有一个对父对象的引用),而且如果使用得当(少于十几行代码并且没有嵌套),它更容易阅读代码.

I thought it made programs run faster (only one reference to parent object) and that it was easier to read the code if used sensibly (less than a dozen lines of code and no nesting).

这是一个例子:

procedure TBitmap32.FillRectS(const ARect: TRect; Value: TColor32);
begin
  with ARect do FillRectS(Left, Top, Right, Bottom, Value);
end;

我喜欢使用 with.我怎么了?

I like using with. What's wrong with me?

推荐答案

使用 with 的一个烦恼是调试器无法处理它.所以这让调试变得更加困难.

One annoyance with using with is that the debugger can't handle it. So it makes debugging more difficult.

一个更大的问题是它不太容易阅读代码.特别是如果 with 语句有点长.

A bigger problem is that it is less easy to read the code. Especially if the with statement is a bit longer.

procedure TMyForm.ButtonClick(...)
begin
  with OtherForm do begin
    Left := 10;
    Top := 20;
    CallThisFunction;
  end;
end;

哪个Form的CallThisFunction会被调用?自我(TMyForm)或其他形式?如果不检查 OtherForm 是否有 CallThisFunction 方法,您就无法知道.

Which Form's CallThisFunction will be called? Self (TMyForm) or OtherForm? You can't know without checking if OtherForm has a CallThisFunction method.

最大的问题是你可以在不知情的情况下轻松解决错误.如果 TMyForm 和 OtherForm 都有 CallThisFunction,但它是私有的,该怎么办.您可能期望/希望调用 OtherForm.CallThisFunction,但事实并非如此.如果您没有使用 with ,编译器会警告您,但现在没有了.

And the biggest problem is that you can make bugs easy without even knowing it. What if both TMyForm and OtherForm have a CallThisFunction, but it's private. You might expect/want the OtherForm.CallThisFunction to be called, but it really is not. The compiler would have warned you if you didn't use the with, but now it doesn't.

在 with 中使用多个对象会使问题成倍增加.请参阅 http://blog.marcocantu.com/blog/with_harmful.html

Using multiple objects in the with multiplies the problems. See http://blog.marcocantu.com/blog/with_harmful.html

这篇关于为什么我不应该使用“with"?在德尔福?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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