And*_*nko 12 .net c# dispose idisposable
当调用Dispose()了IDisposable由对象所拥有的对象?
public class MyClass
{
public MyClass()
{
log = new EventLog { Source = "MyLogSource", Log = "MyLog" };
FileStream stream = File.Open("MyFile.txt", FileMode.OpenOrCreate);
}
private readonly EventLog log;
private readonly FileStream stream;
// Other members, using the fields above
}
Run Code Online (Sandbox Code Playgroud)
我应该Finalize()为这个例子实现吗?如果我什么都不执行怎么办?会有问题吗?
我的第一个想法是MyClass应该实施IDisposable.但是MSDN文章中的以下陈述让我感到困惑:
仅在直接使用非托管资源时才实现IDisposable.如果您的应用只使用实现IDisposable的对象,请不要提供IDisposable实现.
这种说法有误吗?
Mar*_*ell 25
如果MyClass 拥有一个IDisposable资源,那么MyClass它本身应该是IDisposable,并且它应该在Dispose()被调用时处置封装的资源MyClass:
public class MyClass : IDisposable {
// ...
public virtual void Dispose() {
if(stream != null) {
stream.Dispose();
stream = null;
}
if(log != null) {
log.Dispose();
log = null;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不,你不应该在这里实现终结器.
注意:另一种实现可能是这样的:
private static void Dispose<T>(ref T obj) where T : class, IDisposable {
if(obj != null) {
try { obj.Dispose(); } catch {}
obj = null;
}
}
public virtual void Dispose() {
Dispose(ref stream);
Dispose(ref log);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2042 次 |
| 最近记录: |