问题描述
接口 IDisposable
的目的是有序释放非托管资源。它与 using
关键字并驾齐驱,该关键字定义了一个范围,在该范围结束后将处理有问题的资源。
The purpose of the interface IDisposable
is to release unmanaged resources in an orderly fashion. It goes hand in hand with the using
keyword that defines a scope after the end of which the resource in question is disposed of.
由于这种机制非常巧妙,我一再被诱惑让类实现 IDisposable
以便能够以非预期的方式滥用此机制。例如,可以实现一个类来处理嵌套上下文,例如:
Because this meachnism is so neat, I've been repeatedly tempted to have classes implement IDisposable
to be able to abuse this mechanism in ways it's not intended for. For example, one could implement classes to handle nested contexts like this:
class Context : IDisposable
{
// Put a new context onto the stack
public static void PushContext() { ... }
// Remove the topmost context from the stack
private static void PopContext() { ... }
// Retrieve the topmost context
public static Context CurrentContext { get { ... } }
// Disposing of a context pops it from the stack
public void Dispose()
{
PopContext();
}
}
调用代码的用法可能像这样:
Usage in calling code might look like this:
using (Context.PushContext())
{
DoContextualStuff(Context.CurrentContext);
} // <-- the context is popped upon leaving the block
(请请注意,这只是一个示例,而不是这个问题的主题。)
(Please note that this is just an example and not to the topic of this question.)
Dispose()
在离开 using
语句的范围时被调用,也可以利用它来实现各种取决于范围的事物,例如计时器。这也可以通过使用 try ...最终
构造来处理,但是在那种情况下,程序员将不得不手动调用某些方法(例如 Context .Pop
),使用使用
的构造可以完成thon。
The fact that Dispose()
is called upon leaving the scope of the using
statement can also be exploited to implement all sorts of things that depend on scope, e.g. timers. This could also be handled by using a try ... finally
construct, but in that case the programmer would have to manually call some method (e.g. Context.Pop
), which the using
construct could do for thon.
这种用法 IDisposable
的用途与预期目的不符,但这种诱惑仍然存在。
This usage of IDisposable
does not coincide with its intended purpose as stated in the documentation, yet the temptation persists.
是否有具体的理由来说明这是一个坏主意,并永久消除我的幻想,例如垃圾回收的复杂性,异常处理等。或者我应该继续并以此方式滥用这种语言概念来沉迷自己?
Are there concrete reasons to illustrate that this is a bad idea and dispell my fantasies forever, for example complications with garbage collection, exception handling, etc. Or should I go ahead and indulge myself by abusing this language concept in this way?
推荐答案
因此在asp.net MVC视图中,我们看到了以下结构:
So in asp.net MVC views, we see the following construct:
using(Html.BeginForm())
{
//some form elements
}
滥用?微软拒绝(间接)拒绝。
An abuse? Microsoft says no (indirectly).
如果您有一个构造, 需要 完成此操作后, IDisposable
通常可以很好地解决问题。我已经多次这样做了。
If you have a construct that requires something to happen once you're done with it, IDisposable
can often work out quite nicely. I've done this more than once.
这篇关于是否可以滥用ID来从“使用”广告中受益?声明是否有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!