c# - 如何访问我在该 block 外的 using block 中填充的变量?

标签 c# dispose using-statement

我有一个 Xmlreader,我想将其加载到“使用”中的 XMLDocument 中: 但是,问题是 XMLDocument 在完成后(在 xml.Load(reader) 之后)被处理掉。 我试过在“使用”中包含一个 int 变量,它也被处理掉了。 但是,在我创建“结果”字符串的第一个“使用”中,它在离开语句后不会被处理掉。 为什么会这样?

        HttpWebRequest req = WebRequest.Create(URL_GET.ToString()) as HttpWebRequest;
        string result = null;
        using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            result = reader.ReadToEnd();
        }            
        using (XmlReader reader = XmlReader.Create(new StringReader(result)))
        {
            reader.ReadToFollowing("ops:output");
            XmlDocument xml = new XmlDocument();
            xml.Load(reader);
        }

最佳答案

xml 没有被释放;它只是超出了范围,所以 变量 不再可访问 - 但是,它所引用的对象没有发生任何事情。只需在 using 范围之外声明 xml:

XmlDocument xml;
using (XmlReader reader = XmlReader.Create(new StringReader(result)))
{
    reader.ReadToFollowing("ops:output");
    xml = new XmlDocument();
    xml.Load(reader);
}
// Now, xml exists here

关于c# - 如何访问我在该 block 外的 using block 中填充的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24064360/

相关文章:

c# - 在 C# 中处理对象的正确方法?

c++ - 使用命名空间问题

c# - 这个 Dictionary 初始值设定项有什么问题

c# - 选择n级连接度内的所有用户

c# - 是否可以强制将 "using"用于一次性类(class)?

entity-framework - Entity Framework - 我应该如何实例化我的 "Entities"对象

c# - using关键字和IDisposable接口(interface)有什么关系?

c# - 初始化服务时如何实现using语句?

c# - 如何在 Visual Studio IDE 中预览 win 表单设计

c# - .RemoveAll 和 .Where 在 C# 中的性能差异