使用未分配的局部变量“total”
我想要所有间隔的总和,但我编写此代码时出现错误说明:使用未分配的局部变量 total
?
enter TimeSpan total;
foreach (var grp in query)
{
TimeSpan interval = TimeSpan.FromMinutes(grp.Minuut);
TimeSpan intervalH = TimeSpan.FromHours(grp.Sum);
interval = interval + intervalH;
total += interval;
string timeInterval = interval.ToString();
dataGridView2.Rows.Add(i++, grp.Id, grp.Sum, grp.Minuut,timeInterval);
}
I want to have a sum of all intervals , but I write this code I have an error stating: use of unassigned local variable total
?
enter TimeSpan total;
foreach (var grp in query)
{
TimeSpan interval = TimeSpan.FromMinutes(grp.Minuut);
TimeSpan intervalH = TimeSpan.FromHours(grp.Sum);
interval = interval + intervalH;
total += interval;
string timeInterval = interval.ToString();
dataGridView2.Rows.Add(i++, grp.Id, grp.Sum, grp.Minuut,timeInterval);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先:
增加一个没有值的变量是没有意义的。所以这是一个编译器错误是很自然的。
虽然字段初始化为0,但局部变量必须在首次读取之前进行赋值。在您的程序中,
total += Interval;
读取total
以便递增它。因此,在循环的第一次迭代中,它不会被分配值。Start with:
Incrementing a variable that has no value makes no sense. So it's only natural for this to be a compiler error.
While fields get initialized to 0, local variables must be assigned to before they are first read. In your program
total += interval;
readstotal
in order to increment it. In the first iteration of your loop it thus wouldn't have been assigned a value.当总计根本没有分配值时是错误的...您还要添加什么间隔?
Is wrong when total has no value assigned at all... What are you going to add interval too?
您应该在使用前初始化总值,
然后代码应该可以工作。
You should initialize total value before use
then code should work.
从未将初始值分配给总计。使用前必须先赋值。
No initial value is ever assigned to total. You have to assign a value before you use it.