【问题标题】:type use in using statment must be convertible to implicit System.Disposableusing 语句中的类型使用必须可转换为隐式 System.Disposable
【发布时间】:2016-04-08 16:10:00
【问题描述】:

我不明白这个错误。它似乎遵循 MSDN 声明使用。

               public void html() 
    {
        try
        {
            System.Net.WebRequest request = ((System.Net.WebRequest)System.Net.WebRequest.Create("http://url"));
            using (System.Net.WebResponse response = ((System.Net.WebResponse)request.GetResponse()))
            using (System.IO.Stream stream = response.GetResponseStream())
            {
                System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");


                using (System.IO.StreamReader readStream = new System.IO.StreamReader(stream, encoding))
                {
                    System.Windows.Forms.MessageBox.Show(readStream.ReadToEnd());
                    return;
                }
            }
        }
        catch (System.Net.WebException webEx)
        {
            System.Windows.Forms.MessageBox.Show("Errore nella connessione - " + webEx.Message);
        }
    }

如何写一个隐式的 Disposable ?

【问题讨论】:

  • 从您得到该错误的地方删除 using 语句。只写普通变量。

标签: c# using idisposable using-statement


【解决方案1】:

System.Net.WebRequest 没有实现 IDisposable,因此不能在 using 语句中使用它。一个普通的变量声明应该没问题。

System.Net.WebRequest request = System.Net.WebRequest.Create("http://url");

using (System.Net.WebResponse response = ((System.Net.WebResponse)request.GetResponse()))
using (System.IO.Stream stream = response.GetResponseStream())
{
   System.Text.Encoding encoding = System.Text.Encoding.GetEncoding("utf-8");
}

【讨论】:

  • 谢谢,但我在 MSDN WebResponse 上读到没有实现 IDisposable public class HttpWebResponse : WebResponse, ISerializable 为什么使用运行良好 using (System.Net.WebResponse response = ((System.Net.WebResponse)request.GetResponse())) ???
  • @rul3z 因为 HttpWebResponse 继承自 WebResponse。 WebResponse 然后实现 IDisposable。
【解决方案2】:

System.Net.WebRequest 没有实现 IDisposable。您需要删除包装该变量的 using() 语句,错误就会消失。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多