我有几个NumericUpDowns(又名SpinButtons),名为hrsMnu,minMnu,secMnu,msMnu。我正在调用一个将Value属性作为参数的函数。我在班级调用该函数。但是,编译器给了我一个错误:
字段初始值设定项无法引用非静态字段,方法或属性,CountdownTimer.Form1.hrsMnu
我需要在类级别调用该函数。这是我的代码:
int hours = Convert.ToInt16(hrsMnu.Value);
int mins = Convert.ToInt16(minMnu.Value);
int secs = Convert.ToInt16(secMnu.Value);
int mss = Convert.ToInt16(msMnu.Value);
int ms = ToMs(hours, mins, secs, mss);//function I am calling
private void timer_Tick(object sender, EventArgs e)
{
int hours = Convert.ToInt16(hrsMnu.Value);
int mins = Convert.ToInt16(minMnu.Value);
int secs = Convert.ToInt16(secMnu.Value);
int mss = Convert.ToInt16(msMnu.Value);
if (ms == 0)
{
MessageBox.Show("Time is up!");
return;
}
ms--;
}
private int ToMs(int hrs, int mins, int secs, int ms)
{
int fmins = hrs * 60 + mins;
int fsecs = fmins * 60 + secs;
return fsecs * 1000 + ms;
}
注意:我正在制作计时器应用程序。这是主要代码。
答案 0 :(得分:2)
不要为此向表单类添加字段。只是做:
private void timer_Tick(object sender, EventArgs e)
{
int hours = Convert.ToInt16(hrsMnu.Value);
int mins = Convert.ToInt16(minMnu.Value);
int secs = Convert.ToInt16(secMnu.Value);
int mss = Convert.ToInt16(msMnu.Value);
int ms = ToMs(hours, mins, secs, mss);//function I am calling
if (ms == 0)
{
return;
}
ms--;
}
private int ToMs(int hrs, int mins, int secs, int ms)
{
int fmins = hrs * 60 + mins;
int fsecs = fmins * 60 + secs;
return fsecs * 1000 + ms;
}
虽然我没有看到重点,因为你在计算它之后做 1>}。