【问题标题】:C# integer variable in foreach loop [closed]foreach循环中的C#整数变量[关闭]
【发布时间】:2012-09-11 21:25:08
【问题描述】:

在 C# 中,我有一个 foreach 循环,我想在其中 ++ 一个整数。

代码是这样的:

private void btnClick(object sender, EventArgs e) 
{
   int Counter = 0;
   foreach (SettingsProperty currrentProperty in Properties.Settings.Default.Properties)
   {
      Counter++;
   }
   lblText.Text = Counter.ToString();
}

简单,但当然因为我必须将整数赋值为 0,否则编译器会出错。所以lblText.Text 向我打印 0。

我就是不能让它正常工作.. 当然这很容易,但我找不到遮阳篷。

【问题讨论】:

  • 你确定Properties.Settings.Default.Properties 不为空吗?
  • @MarcGravell 我相信他说的是如果声明缺少赋值,编译器会引发明确的赋值错误 (int Counter; ...)
  • @phoog 好吧,代码如图所示不会受到“明确分配”的影响,因此我认为我们应该首先获得更多信息。
  • 您确定没有 Properties.Settings.Default.Properties.Count() 已经为您执行此操作吗?
  • int Counter = Properties.Settings.Default.Properties.Count;

标签: c# variables foreach integer


【解决方案1】:

我认为Properties.Settings.Default.Properties 是空的。所以要确保它是空的,试试:

private void btnClick(object sender, EventArgs e) 
{  
   if(Properties.Settings.Default.Properties.Count != 0)
   {
      int Counter = 0;
      foreach (SettingsProperty currrentProperty in Properties.Settings.Default.Properties)
      {
         Counter++;
         //Some stuff here else just use .Count without use a foreach
      }
      lblText.Text = Counter.ToString();
   } 
   else
      throw new Exception("Properties.Settings.Default.Properties is empty");
}

在编译代码之前尝试设置一些断点

【讨论】:

    猜你喜欢
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多