无法调用Dispose? [英] Unable to call Dispose?

查看:878
本文介绍了无法调用Dispose?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这其中混淆了我一点点......试图处理一个XmlReader的

This one has confused me a little... Attempting to dispose of an XmlReader

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

提供了以下错误:

Provides the following error:

System.Xml.XmlReader.Dispose(布尔)'是无法访问,因为它   保护等级

'System.Xml.XmlReader.Dispose(bool)' is inaccessible due to its protection level

不过,以下是罚款:

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

当我看到在反射器的定义,我不明白为什么我不能调用Dispose

When I look at the definition in Reflector I can't understand why I can't call Dispose

处置的执行情况:

任何人都可以指出我错过了什么?

Can anyone point out what I'm missing?

推荐答案

问题是,的XmlReader 使用的显式接口实现的到的实施的IDisposable 。所以,你的可以的写:

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.

编辑:如前所述,这是在.NET 4.5固定的,因为它暴露了一个的公共的无参数处置方法作为.NET 4.5,以及明确的接口实现。所以presumably你编译在.NET 4.0或更早版本(可能是.NET 2.0给你的标签),但使用反射在.NET 4.5?

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?

这篇关于无法调用Dispose?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆