在整个代码中使用int
问题描述:
我正在尝试制作一个基本计时器,但我无法访问变量。在整个代码中使用int
public void Mins_TextChanged(object sender, EventArgs e)
{
var mintues = Convert.ToInt32(Mins.Text);
}
public void Seconds_TextChanged(object sender, EventArgs e)
{
var second = Convert.ToInt32(Seconds.Text);
}
public void button1_Click(object sender, EventArgs e)
{
timeLeft = (second+456);
timer1.Start();
}
答
使用全局变量。从函数外部声明变量。 示例
public partial class Form1 : Form
{
int minutes;
int second;
public void Mins_TextChanged(object sender, EventArgs e)
{
minutes = Convert.ToInt32(Mins.Text);
}
public void Seconds_TextChanged(object sender, EventArgs e)
{
second = Convert.ToInt32(Seconds.Text);
}
}
到底发生了什么问题?有没有错误信息? – Jasen
请更精确。你的代码应该做什么?什么不工作? – rickythefox
您应该使用Int.TryParse,因为如果输入非数字,该字段为空,或者值为 int.MaxValue,则两个TextChanged方法都会引发异常 –
john