我有一个命名为Property的属性A
,它是AAA
通过Visual Studio中的Properties Setting窗口(项目→Properties→Settings)设置为该值的。
我可以A
使用此循环获取属性的原始值。
如果我更改了值,比如说NewValue
,我可以使用以下代码获取新值:
Properties.Settings.Default.A
但是,在循环中,我不知道如何在不使用语法的情况下获取当前属性值:
Properties.Settings.Default.VariableName
例如:
Properties.Settings.Default.A= "NewValue";
Properties.Settings.Default.Save();
foreach (SettingsProperty _currentProperty in Properties.Settings.Default.Properties)
{
Console.WriteLine(_currentProperty.Name + "," + _currentProperty.DefaultValue.ToString());
}
上面的循环显示了属性的原始值(旧的默认值是AAA
)。
我已经检查了user.config
文件并确保它正在显示NewValue
。
我假设必须有某种方法可以使用我不知道的属性或方法来引用当前值(也许我应该迭代另一个集合?)。
问题是,如何在foreach
上面的循环中显示此新值?
当前Properties.Settings值在返回SettingsPropertyValueCollection查询时类SettingsProvider(如果没有提供者用于设置定义,默认提供程序,LocalFileSettingsProvider,被使用)。
当前代码正在修改设置的值,然后在将设置保存到本地存储之后检查这些值。
代码Properties.Settings.Default.Properties
对与ApplicationSettingsBase.Properties属性相对应的SetsPropertyCollection集合(包含SettingsProperty对象)进行迭代,该集合包含内部用于表示配置属性的元数据的SettingsProperty对象。
此类只能返回关联设置的默认值。
要检查与“属性设置”关联的当前值,该代码应改为迭代SettingsPropertyValueCollection
由ApplicationSettingsBase.PropertyValues属性返回的上述属性,该属性枚举SettingsPropertyValue
对象。这些对象
的PropertyValue属性返回当前分配给Setting的运行时值。
要返回当前值,可以在以下位置修改代码:
foreach (SettingsPropertyValue prop in Properties.Settings.Default.PropertyValues) {
Console.WriteLine($"{prop.Name} -> {prop.PropertyValue}");
}
有关“应用程序设置”的一些注意事项:
应用程序设置分为两个主要类别:
Application
作用域中的设置)为app.config
文件中,该[Application].exe.config
文件在构建项目时复制到文件中。用户设置(User
范围内的设置)(适用于Visual Studio 2017+)
这些设置与应用程序设置一起存储,但是具有关联的本地存储文件,用于存储用户(或应用程序)在运行时可以更改的值,时间:
2.1如果设置的属性设置为,则此部分中user.config
当前用户配置文件中存储的文件。2.2如果将设置属性设置为,则此部分中当前用户配置文件中存储的文件。
[User]/AppData/Local/[CompanyName]/[ProductName].exe_<hash>/[Assembly Version]
Roaming
false
user.config
[User]/AppData/Roaming/[CompanyName]/[ProductName]/[File Version]
Roaming
true
将新值分配给“设置”时,不会修改User
范围中设置的原始值即Default
值。
用户范围中的设置可以使用ApplicationSettingsBase.Save()方法保存在运行时分配的新值:
Properties.Settings.Default.Save();
应用程序可以使用ApplicationSettingsBase.Reload()方法重新加载上次保存的值(也许是放弃最近的更改):
Properties.Settings.Default.Reload();
要放弃对用户设置所做的所有更改,可以使用ApplicationSettingsBase.Reset()方法将“设置”重置为默认值:
Properties.Settings.Default.Reset();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句