foreach循环中的C#整数变量

时间:2012-09-11 21:25:08

标签: c# variables foreach integer

在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。

我无法让它正常工作.. 当然这是一个简单的,但我找不到一个太棒了。

1 个答案:

答案 0 :(得分: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");
}

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