我已经创建了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; // :((
}
}
}发布于 2015-09-27 13:21:16
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
发布于 2016-04-05 15:53:15
不幸的是,另一个解决方案将运行,但是不正确的。您可以通过比较来确认这一点:
Properties.Settings.Default.Properties[c.name].DefaultValue和Properties.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;
}
}https://stackoverflow.com/questions/32778869
复制相似问题