我不知道如何制作通用设置类,希望您能帮助我。
首先,我想要一个单一的设置文件解决方案。为此,我创建了一个像这样的单例:
public sealed class Settings
{
private static readonly Lazy<Settings> _instance = new Lazy<Settings>(() => new Settings());
private Dictionary<string, object> m_lProperties = new Dictionary<string, object>();
public void Load(string fileName)
{
throw new NotImplementedException();
}
public void Save(string fileName)
{
throw new NotImplementedException();
}
public void Update()
{
throw new NotImplementedException();
}
/// <summary>
/// Gets the propery.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <returns></returns>
public string GetPropery(string propertyName)
{
return m_lProperties[propertyName].ToString() ?? String.Empty;
}
/// <summary>
/// Gets the propery.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public string GetPropery(string propertyName, string defaultValue)
{
if (m_lProperties.ContainsKey(propertyName))
{
return m_lProperties[propertyName].ToString();
}
else
{
SetProperty(propertyName, defaultValue);
return defaultValue;
}
}
/// <summary>
/// Sets the property.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
/// <param name="value">The value.</param>
public void SetProperty(string propertyName, string value)
{
if (m_lProperties.ContainsKey(propertyName))
m_lProperties[propertyName] = value;
else
m_lProperties.Add(propertyName, value);
}
}
但我认为更好的方法是属性在类中,我可以通过反射获取属性。
- 你能帮我实现这样的事情吗?
- 是否可以提供诸如“encrypted = true”之类的属性属性?- 在 xml 文件中保存/加载设置的最佳方式是什么?
更新
这里是一个如何使用实际设置的示例:
class Test()
{
private string applicationPath;
private string configurationPath;
private string configurationFile;
public Test()
{
applicationPath = Settings.Instance.GetPropery("ApplicationPath", AppDomain.CurrentDomain.BaseDirectory);
configurationPath = Settings.Instance.GetPropery("ConfigurationPath", "configurations");
configurationFile = Settings.Instance.GetPropery("ConfigurationFile", "application.xml");
// ... Load file with all settings from all classes
}