Nett
Nett copied to clipboard
Save/Load Dictionary<ENUM, string>
Hi all,
how is it possible to save and restore a dictionary with an enumeration type key and a string value?
I already tried to create custom settings and register a custom conversion with ConfigureType. Can somebody help me out?
Thanks in advance Philipp
public enum TheEnum
{
A,
B,
}
public class Foo
{
public Dictionary<TheEnum, string> D { get; set; } = new Dictionary<TheEnum, string>();
}
[Fact]
public void Foooxy()
{
var foo = new Foo();
foo.D.Add(TheEnum.A, "a");
foo.D.Add(TheEnum.B, "b");
var conf = TomlSettings.Create(cfg => cfg
.ConfigureType<Dictionary<TheEnum, string>>(tc => tc
.WithConversionFor<TomlTable>(conv =>
conv.FromToml(ConvertFromToml)
.ToToml(ConvertToToml))));
var w = Toml.WriteString(foo, conf);
var r = Toml.ReadString<Foo>(w, conf);
r.D[TheEnum.A].Should().Be("a");
static Dictionary<TheEnum, string> ConvertFromToml(ITomlRoot root, TomlTable table)
{
var result = new Dictionary<TheEnum, string>();
foreach(var r in table.Rows)
{
var key = (TheEnum)Enum.Parse(typeof(TheEnum), r.Key);
result.Add(key, r.Value.Get<string>());
}
return result;
}
static void ConvertToToml(Dictionary<TheEnum, string> d, TomlTable t)
{
foreach(var kvp in d)
{
t.Add(kvp.Key.ToString(), kvp.Value);
}
}
}