在c#中使局部变量值全局
本文关键字:变量值 全局 使局 | 更新日期: 2023-09-27 18:14:08
我有以下代码。在这段代码中,我能够通过使用eventHandling获得字符串值,如1,2,3等。我如何得到这个值现在并不重要。我现在需要的是能够在page_load事件之外访问这个字符串值,就像下面给出的函数myfun()
一样。我怎样才能做到呢?
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.
}
我看到有两种方法:
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)创建一个类变量:
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
}
根据我的经验,您只需在函数作用域之外声明您想要全局的变量。
IE: Whatever/where they are contains。
string st; // St is declared outside of their scopes
protected void Page_Load(object sender, EventArgs e)
{}
protectd void myfun()
{
}
可以设置为public:
public—成员可以从任何地方访问。这是限制最少的可见性。默认情况下,枚举和接口是公开可见的
<visibility> <data type> <name> = <value>;
或
public string name = "John Doe";
将全局变量(或类?)放在Page_Load之前或class声明之后。
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;
}
}
一个简单的改变就可以使它成为可能。声明STR为全局变量
public class Form1
{
string str = "";//Globel declaration of variable
protected void Page_Load(object sender, EventArgs e)
{
}
}