在运行时遍历 properties.settings

Iterate through properties.settings in runtime

我创建了 32 properties.settings 类型的 int32[]。 我将在运行时使用它们——读取和写入一些数据并使用 foreach 命令检查每个设置值。我在遍历属性值时遇到一些问题。 这是我的代码:

 private void button1_Click(object sender, EventArgs e)
 {
     foreach (SettingsProperty c in Properties.Settings.Default.Properties)
     {
         if (c[0,0]==0)     // i can not reach this byte :(
         {
                c[0, 0] = 1;   // :((
         }
     }
}

SettingsProperty 的值存储在其 DefaultValue 属性 中。尝试以下操作:

private void button1_Click(object sender, EventArgs e)
{
  foreach (SettingsProperty c in Properties.Settings.Default.Properties)
  {
    if (c.DefaultValue[0,0] == 0)
    {
      c.DefaultValue[0, 0] = 1;
    }
  }
}

您可能还想使用 Linq 简化代码:

private void button1_Click(object sender, EventArgs e)
{
  foreach (SettingsProperty c in Properties.Settings.Default.Properties
                                                .Cast<object>()
                                                .Where(c => ((int[,])((SettingsProperty)c).DefaultValue)[0, 0] == 0))
  {
    c.DefaultValue[0, 0] = 1;
  }
}

或者在一行代码中更好:

private void button1_Click(object sender, EventArgs e)
{
  Properties.Settings.Default.Properties.Cast<object>()
                                        .Where(c => ((int[,])((SettingsProperty)c).DefaultValue)[0, 0] == 0)
                                        .ToList()
                                        .ForEach(c => ((int[,])((SettingsProperty)c).DefaultValue)[0, 0] = 1);

  // .ToList() is added because .ForEach() is not available on IEnumerable<T>
  // I added .Cast<object>() to convert from IEnumerable to IEnumerable<object>. Then I use the cast to SettingsProperty so you can use the DefaultValue.
}

最后,这个问题可能会有帮助: C# How to loop through Properties.Settings.Default.Properties changing the values

不幸的是,其他解决方案 运行,但不正确。您可以通过比较来确认这一点:

Properties.Settings.Default.Properties[c.name].DefaultValueProperties.Settings.Default[c.name],发现如果 属性 被赋予了新值,它们是不同的——即使它已被保存。

DefaultValue不存储当前值;只有全局范围内的默认值

要获得实际值,您必须迭代 Properties.Settings.Default.PropertyValues。像这样:

foreach(SettingsPropertyValue value in Properties.Settings.Default.PropertyValues )
{
  if (value.PropertyValue[0,0] == 0)
  {
    value.PropertyValue[0, 0] = 1;
  }
}