自定义SettingsProvider并检索默认值
我已经实现了自己的类,该类继承自 SettingsProvider 类。如果我检索的值尚未由用户设置,即这是程序第一次启动,我会尝试获取默认值。我看到的问题是,当从 SettingsProperty 检索默认值时,它会以字符串形式返回。我尝试添加一些转换项目的代码,但在转换 System.Drawing.Colors 时遇到问题,并收到错误“从‘System.String’到‘System.Drawing.Color’的转换无效。”。
这是我用来获取默认值的代码示例:
private object GetDefaultValue(SettingsProperty setting)
{
if (setting.PropertyType.IsEnum)
return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());
// Return the default value if it is set
if (setting.DefaultValue != null)
return Convert.ChangeType(setting.DefaultValue, setting.PropertyType);
else // If there is no default value return the default object
return Activator.CreateInstance(setting.PropertyType);
}
如何正确地将默认值转换为正确的类型?
I have implemented my own class that inherits from the SettingsProvider class. If the value I am retrieving has not been set by the user, i.e. it is the first time the program starts, I attempt to grab the default value. The problem I am seeing is when the default value is retrieved from the SettingsProperty it comes back as a string. I have tried to add some code that converts the item but I am running into problems when converting System.Drawing.Colors and am receiving the error "Invalid cast from 'System.String' to 'System.Drawing.Color'.".
Here is an example of the code I am using to get the default value:
private object GetDefaultValue(SettingsProperty setting)
{
if (setting.PropertyType.IsEnum)
return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());
// Return the default value if it is set
if (setting.DefaultValue != null)
return Convert.ChangeType(setting.DefaultValue, setting.PropertyType);
else // If there is no default value return the default object
return Activator.CreateInstance(setting.PropertyType);
}
How can I properly convert the default value to the correct type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好的。所以我找到了答案。您需要根据 settings.PropertyType 实际上创建一个 TypeConverter 实例,而不是使用 Convert.ChangeType。这段代码的工作原理:
Ok. So I found the answer. Instead of using Convert.ChangeType you need to actually create a TypeConverter instance against the settings.PropertyType. This code Works: