C#自定义控件如何通用调用Properties.Settings的Save()方法
解决方案
方法1:通过反射调用Save()方法
所有自动生成的Properties.Settings类都继承自ApplicationSettingsBase,Save()是该基类的方法。无需判断具体Settings对象,直接通过反射调用即可:
修改SetProperty2方法,设置完值后添加以下代码:
// 调用基类的Save()方法 var saveMethod = propertiesObject.GetType().GetMethod("Save", System.Type.EmptyTypes); saveMethod?.Invoke(propertiesObject, null);
无论传入的是Settings.Default、Settings1.Default还是其他Settings对象,都能通用调用保存方法。
方法2:利用ApplicationSettingsBase类型转换(更高效)
既然所有Settings类都继承自ApplicationSettingsBase,可以直接将object类型的propertiesObject转换为该基类类型,直接调用Save(),比反射更高效:
- 替换控件中的
object propertiesObject字段:
private ApplicationSettingsBase _settingsBase;
- 修改
SetupControl方法:
public void SetupControl(string in_thisLabel, ApplicationSettingsBase in_PropertiesObject, string in_propertiesString) { this.thisLabel = in_thisLabel; _settingsBase = in_PropertiesObject; this.propertiesString = in_propertiesString; lblProperty.Text = in_thisLabel; txtPropertyValue.Text = "Empty"; GetDataType(); GetValue(); }
父窗体调用时直接传入Default对象(本身就是ApplicationSettingsBase子类):
thisControl.SetupControl("Speed", Properties.Settings.Default, SPEED_SETTING); thisControl.SetupControl("Volume", Properties.Settings1.Default, VOLUME_SETTING);
- 更新
GetValue和GetDataType方法:
private void GetValue() { string thisValue=""; try { thisValue= _settingsBase[propertiesString]?.ToString() ?? "Empty"; } catch (Exception ex) { thisValue=ex.Message; } txtPropertyValue.Text = thisValue; _value= txtPropertyValue.Text; } private void GetDataType() { var propertyInfo = _settingsBase.Properties[propertiesString]; dataType = propertyInfo.PropertyType.Name; txtDataType.Text = dataType; }
- 修改
SetProperty2方法,直接调用Save():
private void SetProperty2() { this.UpdateValueFromTextBox(); if (_value == "") { return; } var propertyInfo = _settingsBase.Properties[propertiesString]; Type propType = propertyInfo.PropertyType; // 通用类型转换,避免硬编码判断 object convertedValue; try { convertedValue = Convert.ChangeType(_value, propType); } catch { // 类型转换失败的处理,比如提示用户输入格式错误 return; } _settingsBase[propertiesString] = convertedValue; _settingsBase.Save(); // 直接调用保存方法 }
额外优化建议
- 添加类型转换失败的用户提示,比如弹出消息框告知输入格式不正确
- 原
GetDataType方法中Split(" ")[0]的方式不稳定,改用PropertyType.Name更可靠 - 可添加
Reload()方法调用,方便用户将设置重置为默认值
内容的提问来源于stack exchange,提问作者John McCormick
相关产品推荐
相关产品推荐

