C# 如何从第二个函数访问在一个函数中声明的变量?
我是C语言编程新手,正在寻找一个快速的解决方案。我在表单上有两个按钮,一个是调用DownloadFileAsync(),第二个应该取消这个操作。 第一个按钮的代码:C# 如何从第二个函数访问在一个函数中声明的变量?,c#,private-members,downloadfileasync,C#,Private Members,Downloadfileasync,我是C语言编程新手,正在寻找一个快速的解决方案。我在表单上有两个按钮,一个是调用DownloadFileAsync(),第二个应该取消这个操作。 第一个按钮的代码: private void button1_Click(object sender, EventArgs e) { ... WebClient webClient = new WebClient(); webClient.DownloadFileAsync(new Uri(textBox1.Text), destination); }
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 from first函数,以秒为单位)。这不是一个私有变量<代码>网络客户端超出范围。您必须使其成为类的成员变量
class SomeClass {
WebClient webClient = new WebClient();
private void button1_Click(object sender, EventArgs e)
{
...
webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
}
}
webclient是在button1_Click方法中声明的,在该方法的作用域中是可用的 因此,您不能在button2\u Click方法中使用它 相反,编译器将使构建失败
要重新启用此功能,请将webClient声明移到方法之外,并使其在类级别可用您必须在类中全局定义
webClient
(变量范围)<代码>网络客户端上的按钮2\u单击
超出范围
表格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();
}
}
在方法外部声明您的webClient。它不是私有的,而是方法的本地,并且只在方法执行时有效。