【问题标题】:How do I access a variable declared in one function from a second function?如何从第二个函数访问在一个函数中声明的变量?
【发布时间】:2012-07-15 20:45:06
【问题描述】:

我是 C# 编程的新手,我正在寻找一个快速的解决方案。我在表单上有 2 个按钮,一个是调用 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。
  • 它不是私有的,而是方法本地的,并且仅在方法执行时才存在。

标签: c# private-members downloadfileasync


【解决方案1】:

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

class SomeClass {
    WebClient webClient = new WebClient();

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

【讨论】:

    【解决方案2】:

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

    表格 MSDN:Scopes

    local-variable-declaration 中声明的局部变量的范围是该声明所在的块。

    类成员声明所声明的成员的范围是声明所在的类体。

    这样

    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();
        }
    
    }
    

    【讨论】:

      【解决方案3】:

      webclient在button1_Click方法中声明,在该方法范围内可用

      因此你不能在 button2_Click 方法中使用它

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 1970-01-01
        • 2012-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多