无法在此范围内声明变量名称

时间:2011-08-22 02:51:11

标签: c#

我想我到目前为止一切都在运作。如果'req'的局部变量错误...已经在System.Net.WebRequest上面声明了req = null,则会遗留一个错误;但我想在使用WebRequest req = WebRequest.Create之前清除它...我不需要这样做吗?

while (listId.Items.Count > 0)
            {
                // making the first item as selected.
                listId.SelectedIndex = 0;

                foreach (object o in listProxy.Items)
                {
                    string strProxy = o as string;
                    WebProxy proxyObject = new WebProxy(strProxy, true); // insert listProxy proxy here
                    WebRequest.DefaultWebProxy = proxyObject;

                    string strURL = "http://www.zzzz.com"; // link from listId and insert here
                    System.Net.WebRequest req = null;

                    try
                    {
                        WebRequest req = WebRequest.Create(strURL + "/book.php?qid=" + listId.SelectedItem as string);
                        req.Proxy = proxyObject;
                        req.Method = "POST";
                        req.Timeout = 5000;

                    }
                    catch (Exception eq)
                    {
                        string sErr = "Cannot connect to " + strURL + " : " + eq.Message;
                        MessageBox.Show(sErr, strURL, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                }

                // remove the selected item.
                listId.Items.RemoveAt(0);

                // refreshing the list.
                listId.Refresh();
            }

3 个答案:

答案 0 :(得分:7)

您已在外部作用域中声明它,因此无法在内部作用域中重新声明它。无需重新声明WebRequest。删除两个声明之一。我会删除外部范围中的那个,因为看起来你不需要在try块之外引用它。

while (listId.Items.Count > 0)
{
    // making the first item as selected.
    listId.SelectedIndex = 0;

    foreach (object o in listProxy.Items)
    {
        string strProxy = o as string;
        WebProxy proxyObject = new WebProxy(strProxy, true); // insert listProxy proxy here
        WebRequest.DefaultWebProxy = proxyObject;

        string strURL = "http://www.zzzz.com"; // link from listId and insert here

        try
        {
            WebRequest req = WebRequest.Create(strURL + "/book.php?qid=" + listId.SelectedItem as string);
            req.Proxy = proxyObject;
            req.Method = "POST";
            req.Timeout = 5000;
        }
        catch (Exception eq)
        {
            string sErr = "Cannot connect to " + strURL + " : " + eq.Message;
            MessageBox.Show(sErr, strURL, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    }

    // remove the selected item.
    listId.Items.RemoveAt(0);

    // refreshing the list.
    listId.Refresh();
}

答案 1 :(得分:4)

变化:

WebRequest req = WebRequest.Create(strURL + "/book.php?qid=" + listId.SelectedItem as string);

要:

   req = WebRequest.Create(strURL + "/book.php?qid=" + listId.SelectedItem as string);

答案 2 :(得分:1)

您不能在同一范围内声明两个具有相同名称的局部变量,因此不要使用WebRequest req = WebRequest.Create(....)使用req = WebRequest.Create(...)