如何从第二个函数访问一个函数中声明的变量



我是C#编程的新手,正在寻找一个快速的解决方案。我在表单上有两个按钮,一个调用DownloadFileAsync(),第二个应该取消此操作。第一个按钮的代码:

private void button1_Click(object sender, EventArgs e)
{
...
WebClient webClient = new WebClient();
webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
}

第二个按钮的代码:

private void button2_Click(object sender, EventArgs e)
{
webClient.CancelAsync(); // yes, sure, WebClient is not known here.
}

我正在寻找一个如何快速解决这个问题的想法(在第二块中使用第一个函数中的webClient)。

这不是一个私有变量。webClient超出范围。您必须将其作为类的成员变量。

class SomeClass {
    WebClient webClient = new WebClient();
    private void button1_Click(object sender, EventArgs e)
    {
        ...
        webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
    }
}

您必须在类(变量范围)中全局定义webClientbutton2_Click上的webClient超出范围。

表单MSDN:范围

在局部变量声明中声明的局部变量的作用域是发生声明的块。

类成员声明所声明的成员的作用域是发生声明的类主体。

因此

class YourClass 
{
     // a member declared by a class-member-declaration
     WebClient webClient = new WebClient();
    private void button1_Click(object sender, EventArgs e)
    {
        //a local variable 
        WebClient otherWebClient = new WebClient();
        webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
    }
    private void button2_Click(object sender, EventArgs e)
    {
        // here is out of otherWebClient scope
        // but scope of webClient not ended
        webClient.CancelAsync();
    }
}

网络客户端在button_Click方法中声明,并且在该方法的作用域中可用

因此,您不能在按钮2_Click方法中使用它

相反,编译器将使您的构建失败

要重新解决此问题,请将webClient声明移到方法之外,并使其在类级别上可用

最新更新