1

我写了一段代码:

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

4 回答 4

4

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

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

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

于 2012-12-05T10:04:58.220 回答
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"));
于 2012-12-05T10:04:29.040 回答
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"));
于 2012-12-05T10:34:36.660 回答
0

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

string html = null;
do {
    html = ...
    ...
} while(html.Contains("data-with-image"));
于 2012-12-05T10:08:30.070 回答