我有以下代码。在这段代码中,我可以通过使用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.
}
答案 0 :(得分:1)
根据我的经验,您只需在函数范围之外声明您想要的全局变量。
IE:无论在何处/何处包含它们。
string st; // St is declared outside of their scopes
protected void Page_Load(object sender, EventArgs e)
{}
protectd void myfun()
{
}
答案 1 :(得分:1)
您可以公开:
公开 - 可以从任何地方联系到该成员。这是限制性最小的可见性。默认情况下,枚举和界面是公开可见的
示例强>
<visibility> <data type> <name> = <value>;
或
public string name = "John Doe";
答案 2 :(得分:1)
将您的全局(或类?)变量放在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;
}
}
答案 3 :(得分:1)
一次改变就可以实现。将str声明为全局变量
public class Form1
{
string str = "";//Globel declaration of variable
protected void Page_Load(object sender, EventArgs e)
{
}
}
答案 4 :(得分:1)
我可以通过两种方式完成这项工作:
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
}