如何使“do”块中声明的变量在“while”中有效?

时间:2012-12-05 10:02:50

标签: c# while-loop

我写了一段代码:

do
{
    string html = new StreamReader(response3.GetResponseStream(),
                                   Encoding.UTF8).ReadToEnd();
    if (html.Contains("link-censored"))
    {
        log("[!] Banned link\r\n");
        return -2; // delete url from txt
    }
    else if (html.Contains("data-with-image"))
    {
        log("[+] Add link\r\n");
    }
    else
    {
        log("[?] Smthng wrong with link\r\n");
        return -2; //-3
    }
}
while (html.Contains("data-with-image"));

但是我有一个错误名称'html'在最后一行的当前上下文中不存在。

4 个答案:

答案 0 :(得分:4)

html的范围是 do {...};只需移动声明:

string html;
do
{
    html = new StreamReader(response3.GetResponseStream(),
                                   Encoding.UTF8).ReadToEnd();
    //...
}
while (html.Contains("data-with-image"));

请注意,我们不需要分配给html - 因为“明确赋值”的规则保证它在到达while时具有值

答案 1 :(得分:3)

字符串变量html的范围在do-while loop的正文范围内,将html定义在循环体的外侧以使其可供condition part访问。

string html = string.Empty; 

do
{
    html = new StreamReader(response3.GetResponseStream(),
                                   Encoding.UTF8).ReadToEnd();
    if (html.Contains("link-censored"))
    {
        log("[!] Banned link\r\n");
        return -2; // delete url from txt
    }
    else if (html.Contains("data-with-image"))
    {
        log("[+] Add link\r\n");
    }
    else
    {
        log("[?] Smthng wrong with link\r\n");
        return -2; //-3
    }
}
while (html.Contains("data-with-image"));

答案 2 :(得分:1)

如果您发现预期的情况,请退出。

string html = string.Empty; 

do
{
    html = new StreamReader(response3.GetResponseStream(),
                                   Encoding.UTF8).ReadToEnd();
    if (html.Contains("link-censored"))
    {
        log("[!] Banned link\r\n");
        return -2; // delete url from txt
    }
    else if (html.Contains("data-with-image"))
    {
        log("[+] Add link\r\n");
        return 0;
    }
    else
    {
        log("[?] Smthng wrong with link\r\n");
        return -2; //-3
    }
}
while (html.Contains("data-with-image"));

答案 3 :(得分:0)

我认为问题是变量“html”只存在于循环内部。 尝试在循环之前声明它:

string html = null;
do {
    html = ...
    ...
} while(html.Contains("data-with-image"));