是否可以在 C# 中强制使用 using 语句
我真的希望能够用某种属性来装饰我的类,该属性将强制使用 using 语句,以便该类始终被安全地处置并避免内存泄漏。 有人知道这样的技术吗?
Would really like to be able to decorate my class with an attribute of some sort that would enforce the use of a using statement so that the class will always be safely disposed and avoid memory leaks. Anyone know of such a technique?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,有一种方法可以做到这一点 - 只允许通过带有委托的静态方法访问您的对象。 作为一个非常简化的示例(显然有许多不同的打开文件的方式 - 读/写等):
如果唯一能够创建一次性对象实例的东西是您自己的类中的方法,您可以确保它们适当使用。 诚然,没有什么可以阻止委托获取引用的副本并稍后尝试使用它,但这并不是完全相同的问题。
当然,这种技术严重限制了您可以对对象执行的操作 - 但在某些情况下它可能很有用。
Well, there's one way you could sort of do it - only allow access to your object via a static method which takes a delegate. As a very much simplified example (as obviously there are many different ways of opening a file - read/write etc):
If the only things capable of creating an instance of your disposable object are methods within your own class, you can make sure they get used appropriately. Admittedly there's nothing to stop the delegate from taking a copy of the reference and trying to use it later, but that's not quite the same problem.
This technique severely limits what you can do with your object, of course - but in some cases it may be useful.
您可以使用 FxCop 来强制执行此规则。 请参阅维基百科以获取快速概述。
You could use FxCop to enforce this rule. See the Wikipedia for a quick overview.
如果要确保对象始终被释放,请将终结器与 IDisposable 结合使用。
但在此之前,请阅读 IDisposable 和终结器,并意识到您通常不需要它们,除非您的类正在执行诸如管理非托管资源的生命周期之类的操作。
使用终结器,无论是否包装在 using 中,您的对象都将“最终”被回收。 using 语句为 IDisposable 提供了便利,允许进行确定性清理。 唯一需要注意的是,具有终结器的对象的清理成本更高,并且通常在等待终结时在内存中停留的时间更长。
ref 我什么时候需要实现终结器或IDisposable?
或者
technorabble:使用 Dispose、Finalizer 和 IDisposable
If you want to ensure your object is always disposed, use a finalizer in combination with IDisposable.
But before you do, read up on IDisposable and finalizers, and be conscious of the fact that you normally don't need them unless your class is doing something like managing the lifetime of an unmanaged resource.
With a finalizer your object will be reclaimed 'eventually' whether wrapped in a using or not. The using statement, which is a convenience for IDisposable, allows deterministic cleanup to take place. The only caveat is that object with finalizers are more expensive to clean up and in general stick around in memory longer while they await finalization.
ref When do I need to implement a finalizer or IDisposable?
or
technorabble: Using Dispose, Finalizers and IDisposable