Unable to call Dispose?

。_饼干妹妹 提交于 2019-12-05 00:27:12

The problem is that XmlReader uses explicit interface implementation to implement IDisposable. So you can write:

XmlReader reader = XmlReader.Create(filePath);
((IDisposable)reader).Dispose();

However, I'd strongly suggest using a using statement anyway. It should be very rare that you call Dispose explicitly, other than within another Dispose implementation.

EDIT: As noted, this is "fixed" in .NET 4.5, in that it exposes a public parameterless Dispose method as of .NET 4.5 as well as the explicit interface implementation. So presumably you're compiling against .NET 4.0 or earlier (perhaps .NET 2.0 given your tags) but using Reflector against .NET 4.5?

using(XmlReader reader = XmlReader.Create(filePath))
{
   foo(reader);
}

is exactly equivalent to

XmlReader reader = XmlReader.Create(filePath);
try 
{
   code(reader);
} 
finally
{
   if(reader != null)
     ((IDisposable)reader).Dispose();
}

The most likely thing is that you haven't posted all of your code - perhaps someone else is calling Dispose() on your object as well, causing an exception in the second call to Dispose()?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!