0

我有以下方法返回一个XmlReader

public XmlReader RequestXML(string endpoint)
{
    using (WebClient request = this.PrepareRequest(RestMethod.GET, null))
    {
        byte[] response = request.DownloadData(this.RestUrl + endpoint);
        using (MemoryStream responseStream = new MemoryStream(response))
        {
            XmlReader xReader = XmlReader.Create(responseStream);
            return xReader;
        }
    }
}

但是,当然,这不起作用,因为MemoryStream在调用代码有机会使用XmlReader. 是否有可能返回XmlReader并仍然处置其底层MemoryStream

我考虑过Action<XmlReader>在我的方法中接受委托(或)作为第二个参数来完成 中的工作using,但这种设计似乎有点尴尬。

另外,我不能只打电话WebClient.DownloadString()

4

1 回答 1

2

如果有疑问使用XmlReaderSettings.CloseInput这个重载:XmlReader.Create(Stream, XmlReaderSettings),像这样......

public XmlReader RequestXML(string endpoint)
{
    using (WebClient request = this.PrepareRequest(RestMethod.GET, null))
    {
        byte[] response = request.DownloadData(this.RestUrl + endpoint);
        MemoryStream responseStream = new MemoryStream(response);
        XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
        xmlReaderSettings.CloseInput = true;
        return XmlReader.Create(responseStream, xmlReaderSettings);
    }
}

这样调用的代码RequestXml不需要负责处理MemoryStream.

于 2013-02-06T00:26:15.127 回答