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

我有一个带有计时器的简单表单,并在其中放置了一个标签。我是c#新手,但我设法将时间存储在字符串中,但我无法在加载表单期间显示此字符串,因为它位于计时器函数中

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;

        }

令人惊叹的!我不知道这是可能的。很好!谢谢你的帮助!我通常建议不要使用“全局”变量,除非您了解它的所有后果。对于任何遇到这个问题的人,我建议阅读作为一个出发点,为什么你应该对全局变量保持谨慎。此外,变量时间>代码>,如上面所示,似乎是一个私有的<代码> Frime类。Hi @丹尼斯。如果这个答案已经解决了你的问题,请点击检查标记来考虑。这向更广泛的社区表明,你已经找到了一个解决方案,并给回答者和你自己带来了一些声誉。没有义务这么做。嗨,莫希特。我不知道这是可能的,对这个社区来说还是新鲜事,但是你的信息肯定对我有帮助,我会记住这一点!谢谢你的帮助!谢谢你的帮助,这太好了!我现在必须进一步了解字符串和私有字符串之间的区别。@Dennis没问题,你需要知道的是“公共和私人以及受保护之间有什么区别?我建议你仔细阅读,因为从现在起它们非常方便:太棒了!“我现在就来看看。”丹尼斯祝你好运,伙计!别忘了接受这个解决方案,我想我看到了现在正在发生的一些困惑。关于C的一件有趣的事情是:。因此,Mohit答案中的示例与本答案中的示例完全相同,只是
time
在这里被指定为
private
(在另一个答案中它是隐式private)。