问题描述
根据 <$ c与使用使用
相比,首选$ c>使用。我在其他地方都听说过(例如,)。为什么是这样?我知道后来添加了 use
。但是有什么区别呢?从表面上看,使用 似乎更有用,因为您可以控制何时调用
Dispose()
,并且可以显式忽略边界值(例如,(fun _-> ...)
)。
According to the last sentence on this MSDN page use
is to be preferred over using
. I've heard it elsewhere (this answer, for example). Why is this? I realize use
was added later. But what's the difference? On the surface, using
seems more useful because you can control when Dispose()
is called, and you can explicitly ignore the bound value (e.g., (fun _ -> ...)
) if needed.
推荐答案
我认为偏爱 use
的原因仅仅是因为语法更简单。许多其他语言构造也可以表示为函数(例如 try .. with
, for
,而
,...)。如果语言设计师添加了更简单的语法,为什么不使用它呢?
I think that the reason for preferring use
is just that the syntax is simpler. Many other language constructs could be expressed as functions (e.g. try .. with
, for
, while
, ...). If the language designers added a simpler syntax, why not use it...
正如我在,即使使用 use
,您也可以精确控制范围。 (这样,即使在类声明的构造函数中,您也可以使用它。)但是大多数时候,自动行为就很好了(这使得构造比在C#中使用)。
As I wrote in the earlier answer you referenced, you can precisely control the scope even when using use
. (And this way, you can use it even in constructors of class declarations.) But most of the time, the automatic behavior is just fine (which makes the construct simpler than using
in C#).
是否使用 use
或<$在需要显式控制范围的情况下,使用c $ c> 是个人喜好的问题。如果您不喜欢 use
的明确范围(我承认,这看起来有些怪异,但对我来说很好用),则可以使用使用
。
Whether you'll use use
or using
in situations where you need to control the scope explicitly is a matter of personal taste. If you don't like the explicit scoping of use
(which looks a bit weird, I admit, but works fine for me), you can use using
.
编辑:在类声明中,您不能例如编写:
In a class declaration, you cannot for example write:
type Foo() =
use a = new Whatever()
// ...
,因为 a
的范围可能是实例。 (尽管我认为这可能很有用,并且可以为您的类型添加 IDisposable
的自动实现)。如果您使用使用
,则不会遇到此类麻烦。
because the scope of a
would be (possibly) the whole lifetime of the instance. (Although I think this could be useful and it could add automatic implementation of IDisposable
to your type). If you use using
, you don't get this sort of trouble.
这篇关于为什么使用比使用更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!