2014-07-22 41 views
0

我有以下代碼。在這段代碼中,我能夠通過使用eventHandling獲得像1,2,3等字符串值。如何獲取值並不重要now.What我現在需要的是能夠訪問這個字符串值在page_load事件之外,如函數myfun(),如下所示。我該如何實現這一目標。在c#中創建一個局部變量值global#

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

你可以做到這一點有兩種方式,我看到:

1)通爲PARAM:

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)使類變量:

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) 
    { 
    } 
}