Nếu bạn không cần phải sử dụng thiết kế cài đặt hoặc chỉnh sửa cài đặt của bạn với một trình soạn thảo văn bản, bạn có thể tạo một lớp đơn giản có nguồn gốc từ ApplicationSettingsBase:
namespace MyNamespace
{
using System.Collections.Generic;
using System.Configuration;
/// <summary>
/// Persistent store for my parameters.
/// </summary>
public class MySettings : ApplicationSettingsBase
{
/// <summary>
/// The instance lock.
/// </summary>
private static readonly object InstanceLock = new object();
/// <summary>
/// The instance.
/// </summary>
private static MySettings instance;
/// <summary>
/// Prevents a default instance of the <see cref="MySettings"/> class
/// from being created.
/// </summary>
private MySettings()
{
// don't need to do anything
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static MySettings Instance
{
get
{
lock (InstanceLock)
{
if (instance == null)
{
instance = new MySettings();
}
}
return instance;
}
}
/// <summary>
/// Gets or sets the parameters.
/// </summary>
[UserScopedSetting]
[SettingsSerializeAs(SettingsSerializeAs.Binary)]
public Dictionary<string, string> Parameters
{
get
{
return (Dictionary<string, string>)this["Parameters"];
}
set
{
this["Parameters"] = value;
}
}
}
}
Bí quyết thực sự là [Cài đặtSerializeAs (SettingsSerializeAs.Binary)] thuộc tính. Hầu hết (tất cả?) Các lớp học có thể được đăng theo cách này, trong đó Cài đặtSerializeAs.String hoặc Cài đặtSerializeAs.Xml sẽ không hoạt động cho Từ điển.
Sử dụng này trong mã của bạn như bạn sẽ cài đặt bình thường:
// this code untested...
MySettings.Instance.Parameters["foo"] = "bar";
MySettings.Instance.Parameters.Save();
MySettings.Instance.Parameters.Reload();
string bar;
if (!MySettings.Instance.Parameters.TryGetValue("foo", out bar))
{
throw new Exception("Foobar");
}
Nếu bạn muốn từ điển để serialize vào một cái gì đó người dùng có thể chỉnh sửa, bạn phải xuất phát từ điển và chơi với TypeConverter (xem Using Custom Classes with Application Settings).
Liên quan: http://stackoverflow.com/questions/2890271/how-to-save-a-liststring-on-settings-default – BrunoLM