C# 如何从另一个函数加载字符串?
我有一个带有计时器的简单表单,并在其中放置了一个标签。我是c#新手,但我设法将时间存储在字符串中,但我无法在加载表单期间显示此字符串,因为它位于计时器函数中C# 如何从另一个函数加载字符串?,c#,string,winforms,timer,C#,String,Winforms,Timer,我有一个带有计时器的简单表单,并在其中放置了一个标签。我是c#新手,但我设法将时间存储在字符串中,但我无法在加载表单期间显示此字符串,因为它位于计时器函数中 public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { timer1.Enabled = true; timer1.Interval = 1000; //clockLab
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1000;
//clockLabel.Text = "00:00:00";
clockLabel.Text = time;
}
private void timer1_Tick(object sender, EventArgs e)
{
string time = DateTime.Now.ToString("hh:mm:ss"); // stored time in string
clockLabel.Text = time;
}
问题是Form1_Load不知道时间字符串。有人能帮助初学者理解如何使其工作吗?您可以将字符串时间变量转换为全局变量,该变量可以在任何地方访问
string time;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1000;
//clockLabel.Text = "00:00:00";
clockLabel.Text = time;
}
private void timer1_Tick(object sender, EventArgs e)
{
time = DateTime.Now.ToString("hh:mm:ss");
clockLabel.Text = time;
}
嗯。。您可以在代码顶部声明私有字符串,如下所示:
private string _time;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Interval = 1000;
//clockLabel.Text = "00:00:00";
clockLabel.Text = _time;
}
private void timer1_Tick(object sender, EventArgs e)
{
_time = DateTime.Now.ToString("hh:mm:ss"); // stored time in string
clockLabel.Text = _time;
}
令人惊叹的!我不知道这是可能的。很好!谢谢你的帮助!我通常建议不要使用“全局”变量,除非您了解它的所有后果。对于任何遇到这个问题的人,我建议阅读作为一个出发点,为什么你应该对全局变量保持谨慎。此外,变量
time
在这里被指定为private
(在另一个答案中它是隐式private)。