Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何访问在块外的using块中填充的变量?_C#_Dispose_Using Statement - Fatal编程技术网

C# 如何访问在块外的using块中填充的变量?

C# 如何访问在块外的using块中填充的变量?,c#,dispose,using-statement,C#,Dispose,Using Statement,我有一个Xmlreader,我想将它加载到“using”中的XMLDocument中: 然而,问题是XMLDocument一旦完成(在xml.Load(reader)之后)就会被释放。 我尝试过在“using”中包含一个int变量,它也被释放了。 但是,在我创建“result”字符串的第一个“using”中,它在离开语句后不会被释放。 为什么会这样 HttpWebRequest req = WebRequest.Create(URL_GET.ToString()) as Http

我有一个Xmlreader,我想将它加载到“using”中的XMLDocument中: 然而,问题是XMLDocument一旦完成(在xml.Load(reader)之后)就会被释放。 我尝试过在“using”中包含一个int变量,它也被释放了。 但是,在我创建“result”字符串的第一个“using”中,它在离开语句后不会被释放。 为什么会这样

        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
无法处理;它只是超出了范围,因此变量不再可访问-但是,它所引用的对象没有发生任何变化。只需使用范围在
之外声明
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

xml
无法处理;它只是超出了范围,因此变量不再可访问-但是,它所引用的对象没有发生任何变化。只需使用
范围在
之外声明
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

int
变量是否被释放?有趣的是,您的代码示例中没有int变量。我是@SergeyBerezovskiy的——我想看一个例子:)你的意思一点也不清楚——我希望读者被处理掉,但不是XmlDocument。值得注意的是,您实际上并没有使用XML文档。您看到什么症状使您相信文档正在被处理?(据我所知,XmlDocument甚至没有实现IDisposable…)您的字符串结果没有得到“释放”,因为您在using语句
int
变量get disposed之外声明并初始化了它?有趣的是,您的代码示例中没有int变量。我是@SergeyBerezovskiy的——我想看一个例子:)你的意思一点也不清楚——我希望读者被处理掉,但不是XmlDocument。值得注意的是,您实际上并没有使用XML文档。您看到什么症状使您相信文档正在被处理?(据我所知,XmlDocument甚至没有实现IDisposable…)您的字符串结果没有得到“释放”,因为您在using语句之外声明并初始化了它。在我之前回答的DAM:P删除了我的答案。@TimBJames:实际上,你比我快了7秒-我没有删除自己答案的唯一原因是我提供了比你多一点的解释。。。不过,我猜你得到了“纪律严明”的徽章;-)@user3472931:您应该仔细阅读有关作用域和使用
语句的
的语法和语义,这是两个不同的概念。在我之前回答:P删除了我的答案。@TimBJames:实际上,你比我快了7秒-我没有删除自己答案的唯一原因是我提供了比你多一点的解释。。。不过,我猜你得到了“纪律严明”的徽章;-)@user3472931:您应该阅读有关作用域和使用
语句的
的语法和语义,这是两个不同的概念。