【发布时间】:2017-07-08 05:05:34
【问题描述】:
我希望能够轻松地将单个用户设置重置为其默认值。 我写了一个这样的扩展:
public static void sReset(this Properties.Settings set, string key = "")
{
if (key == "")
{
set.Reset();
return;
}
Console.WriteLine("Reset '" + key + "' to: " + set.Properties[key].DefaultValue);
set.PropertyValues[key].PropertyValue = set.PropertyValues[key].Property.DefaultValue;
}
这适用于原始类型。 但现在我想将它应用于 stringCollection,但它失败了:
发生了“System.InvalidCastException”类型的未处理异常 在 myApp.exe 中
附加信息:无法转换类型为“System.String”的对象 输入“System.Collections.Specialized.StringCollection”。
这是因为这些集合类型默认值(Stored serialized as XML)作为字符串返回:
set.Properties[key].DefaultValue.GetType() 返回System.String
我可以在设置设计器中看到,通常它只是将值转换为 StringCollection:
public global::System.Collections.Specialized.StringCollection settingsName {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["settingsName"]));
}
set {
this["settingsName"] = value;
}
}
但在分配 DefaultValue 后失败,出现上述错误消息。
我尝试在分配之前强制转换 XML 字符串,但当然也失败了。
在分配给设置属性之前,如何转换这样的 XML 字符串? 我需要做什么才能完成这项工作?
【问题讨论】:
标签: c# visual-studio