首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么ApplicationSettingsBase.Reset()要空PropertyValues?

为什么ApplicationSettingsBase.Reset()要空PropertyValues?
EN

Stack Overflow用户
提问于 2009-10-28 00:34:49
回答 1查看 1.3K关注 0票数 0

我认为Reset()方法再次用默认值重新填充Settings,但似乎并非如此。如何用默认值重新加载它们?

代码语言:javascript
复制
  private void buttonLoadDefaultSettings_Click(object sender, EventArgs e)
  {
   FooSettings.Default.Reset();

   // Data grid will show an empty grid after call to reset.
   DataGridFoo.Rows.Clear();
   foreach (SettingsPropertyValue spv in FooSettings.Default.PropertyValues)
   {
    DataGridFoo.Rows.Add(spv.Name, spv.PropertyValue);
   }
  }

更新

代码语言:javascript
复制
private void buttonLoadDefaultSettings_Click(object sender, EventArgs e)
  {
   foreach (SettingsProperty sp in FooSettings.Default.Properties)
   {
    FooSettings.Default[sp.Name.ToString()] = sp.DefaultValue;
   }

   DataGridFoo.Rows.Clear();
   foreach (SettingsPropertyValue spv in FooSettings.Default.PropertyValues)
   {
    DataGridFoo.Rows.Add(spv.Name, spv.PropertyValue);
   }
  }

删除对Reset()的调用,并手动将属性值设置为默认存储的属性值。我还是很想知道这是应该用的还是我漏掉了什么?

EN

回答 1

Stack Overflow用户

发布于 2010-04-22 21:42:35

我遇到这个帖子是因为我遇到了同样的问题。我想我应该把我的发现报告给未来任何可能来这里的旅行者。我不能保证这是100%准确或完整的,因为我已经摆弄了一个小时了,即使我觉得还有更多的事情要知道,但这一天已经够多了。但至少这里会有一些提示。)

虽然Reset()的文档似乎表明,保存的设置被覆盖在user.config文件中,其中包含来自app.config文件的默认值,但情况似乎并非如此。它只是从user.config文件中删除设置,使用上面的示例,该文件导致FooSettings.Default.PropertyValues的计数为0,因为在使用Reset()之后不存在。但是,有一些方法可以处理这个结果,而不必像OP那样重新填充设置。一种方法是显式检索单个设置值,如下所示:

代码语言:javascript
复制
// This always returns the value for TestSetting, first checking if an
// appropriate value exists in a user.config file, and if not, it uses 
// the default value in the app.config file.
FormsApp.Properties.Settings.Default.TestSetting;

其他方法包括使用SettingsPropertyValueCollection和/或SettingsPropertyCollection

代码语言:javascript
复制
// Each SettingsProperty in props has a corresponding DefaultValue property
// which returns (surprise!) the default value from the app.config file.
SettingsPropertyCollection props = FormsApp.Properties.Settings.Default.Properties;

// Each SettingsPropertyValue in propVals has a corresponding PropertyValue
// property which returns the value in the user.config file, if one exists.
SettingsPropertyValueCollection propVals = FormsApp.Properties.Settings.Default.PropertyValues;

所以,回到原来的问题,你可以做的是:

代码语言:javascript
复制
private void buttonLoadDefaultSettings_Click(object sender, EventArgs e)
{
    FooSettings.Default.Reset();
    DataGridFoo.Rows.Clear();

    // Use the default values since we know that the user settings 
    // were just reset.
    foreach (SettingsProperty sp in FooSettings.Default.Properties)
    {
        DataGridFoo.Rows.Add(sp.Name, sp.DefaultValue);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1634543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档