-4

私は C# でのプログラミングが初めてで、簡単な解決策を探しています。フォームに 2 つのボタンがあり、1 つは DownloadFileAsync() を呼び出しており、2 つ目はこの操作をキャンセルする必要があります。最初のボタンのコード:

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

2 番目のボタンのコード:

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

この問題をすばやく解決する方法を探しています (最初の関数の webClient を 2 番目のブロックで使用します)。

4

3 に答える 3

4

これはプライベート変数ではありません。webClient範囲外になります。これをクラスのメンバー変数にする必要があります。

class SomeClass {
    WebClient webClient = new WebClient();

    private void button1_Click(object sender, EventArgs e)
    {
        ...
        webClient.DownloadFileAsync(new Uri(textBox1.Text), destination);
    }
}
于 2012-07-15T20:46:31.490 に答える
1

webClientクラス(変数のスコープ)でグローバルに定義する必要があります。webClientonbutton2_Clickは範囲外です。

フォームMSDN:スコープ

local-variable-declarationで宣言されたローカル変数のスコープは、宣言が発生するブロックです。

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

}
于 2012-07-15T20:48:56.323 に答える
0

webclientはbutton1_Clickメソッドで宣言されており、このメソッドのスコープで使用できます。

したがって、button2_Clickメソッドでは使用できません

代わりに、コンパイラはビルドに失敗します

これを再利用するには、webClient宣言をメソッドの外に移動し、クラスレベルで使用できるようにしてください。

于 2012-07-15T20:48:42.637 に答える