2014-07-22 2 views
0

다음 코드를 사용합니다.이 코드에서는 eventHandling을 사용하여 1,2,3 등의 문자열 값을 얻을 수 있습니다. 값은 중요하지 않습니다. now.What 필요한 지금은 아래 주어진 함수로 myfun() 같은 page_load 이벤트 외부에서이 문자열 값을 액세스 할 수 있습니다. 내가 어떻게 acheive.로컬 변수 값을 C로 글로벌하게합니다. #

protected void Page_Load(object sender, EventArgs e) 
{ 

    hfm mymaster = (hfm)Page.Master; 
    lcont lc = mymaster.getlcont(); 
    lc.myevent += delegate(string st) 
    { 
     //slbl.Text = st; 

     string str =st; 
     } 
} 

    protectd void myfun() 
    { 
    //i want to access the string value "st" here. 
    } 
+0

위임 범위가 아닌 클래스 범위에서 정의하거나 'myfun()'에 매개 변수로 전달하십시오. –

답변

1

:

protected void Page_Load(object sender, EventArgs e) 
{ 

    hfm mymaster = (hfm)Page.Master; 
    lcont lc = mymaster.getlcont(); 
    lc.myevent += delegate(string st) 
    { 
     //slbl.Text = st; 

     string str =st; 
     myfunc(str); // pass as param 
     } 
} 

protectd void myfun(string str) // see signature 
{ 
    //i want to access the string value "st" here. 
} 

2) 클래스 변수 확인 :

1) PARAM로 전달

string classvariable; 
protected void Page_Load(object sender, EventArgs e) 
{ 

    hfm mymaster = (hfm)Page.Master; 
    lcont lc = mymaster.getlcont(); 
    lc.myevent += delegate(string st) 
    { 
     //slbl.Text = st; 

     string str =st; 
     classvariable = str; // set it here 
    } 
} 

protectd void myfun() 
{ 
    //i want to access the string value "st" here. // get it here 
} 
1

필자가 경험 한 바에 따르면 전역 변수로 사용할 변수를 함수의 범위 밖에 선언하기 만하면됩니다.

IE : 어디에서나 포함됩니다.

string st; // St is declared outside of their scopes 
protected void Page_Load(object sender, EventArgs e) 
{} 
    protectd void myfun() 
    { 
    } 
1

당신은 공개 할 수 있습니다

공공

는 - 회원은 어디서나 접근 할 수 있습니다. 이것은 가장 제한적인 가시성입니다. 열거 형 및 인터페이스는 공개적으로, 기본적으로

예 볼 수 있습니다

<visibility> <data type> <name> = <value>; 

또는

public string name = "John Doe"; 
1

장소를 Page_Load 전이나 바로 클래스 선언 이후 글로벌 (또는 클래스?) 변수 .

public partial class Index : System.Web.UI.Page 
{ 
    private string str = ""; 

    protected void Page_Load(object sender, EventArgs e) 
    { 

     hfm mymaster = (hfm)Page.Master; 
     lcont lc = mymaster.getlcont(); 
     lc.myevent += delegate(string st) 
     { 
      //slbl.Text = st; 

     str =st; 
     } 
    } 

    protectd void myfun() 
    { 
    //i want to access the string value "st" here. 

    //value of st has been passed to str already in page_load. 
    string newString = str; 
    } 

} 
1

단일 변경으로 가능할 수 있습니다. 전역 변수로 str을 선언

내가 보는 바와 같이 두 가지 방법으로 그것을 할 수
public class Form1 
{ 
    string str = "";//Globel declaration of variable 
    protected void Page_Load(object sender, EventArgs e) 
    { 
    } 
}