2012-07-15 4 views
-4

저는 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. 
} 

.

+0

메소드 외부에서 웹 클라이언트를 선언합니다. – Adam

+0

메서드는 private이지만 로컬 메서드는 아니며 메서드가 실행되는 동안에 만 살 수 있습니다. –

답변

5

개인 변수가 아닙니다. webClient이 범위를 벗어납니다. 클래스의 멤버 변수로 만들어야합니다.

class SomeClass { 
    WebClient webClient = new WebClient(); 

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

웹 클라이언트가를 Button1_Click 방법에 선언하고

은 그러므로 당신이

가 대신 컴파일러가 빌드 실패합니다 button2_Click 방법에서 사용할 수없는 범위에서이 방법 avialble입니다

으로 다시 작성하십시오. 메서드 외부에서 webClient 선언을 이동하여 클래스 수준에서 사용할 수있게하십시오.

1

귀사의 클래스에서 globally in webClient입니다 (변수의 범위). webClient (button2_Click)은 범위를 벗어납니다.

형태는 MSDN : Scopes

로컬 변수 선언에서 선언 된 로컬 변수의 범위는 선언이 발생하는 블록이다.

클래스 멤버 선언 선언 멤버들의 범위는 선언이 발생하는 급 기관이다.

은 그래서

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

} 
관련 문제