使用点符号将对象转换为字典

R4n*_*c1d 0 c# dictionary

请找到问题链接的附加小提琴

我想做的是将对象转换为字典该对象看起来像这样

var person = new Person
{
    FirstName = "Jon",
    LastName = "Doe",
    Address = new Address
    {
        Street = "Melkbos",
        PostalCode = 90210
    }
};   
Run Code Online (Sandbox Code Playgroud)

所需的输出应该如下所示

{
 {"FirstName", "Jon"},
 {"LastName", "Doe"},
 {"Address.Street", "Melkbos"},
 {"Address.PostalCode", 90210},
};
Run Code Online (Sandbox Code Playgroud)

因此,如果对象是嵌套的,我想要一个点符号

Jon*_*n B 5

您需要使用递归并测试要序列化的属性的类型。我修改了您的部分代码来执行此操作,使用IsSerializable. 您可能需要调整它以满足您的具体需求:

public static IDictionary<string, T> ToDictionary<T>(this object source)
{
    if (source == null)
        ThrowExceptionWhenSourceArgumentIsNull();

    var dictionary = new Dictionary<string, T>();
    AddPropertiesToDictionary(new List<string>(), source, dictionary);
    return dictionary;
}

private static void AddPropertiesToDictionary<T>(IList<string> path, object source, IDictionary<string, T> dictionary)
{
    foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
    {
        var value = property.GetValue(source);
        if (IsOfType<T>(value))
        {
            if (property.PropertyType.IsSerializable) {
                dictionary.Add((path.Any() ? string.Join(".", path) + "." : "") + property.Name, (T)value);
            }
            else
            {
                path.Add(property.Name);
                AddPropertiesToDictionary(path, value, dictionary);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

Key                Value
FirstName          Jon  
LastName           Doe  
Address.Street     Melkbos 
Address.PostalCode 90210
Run Code Online (Sandbox Code Playgroud)

您应该能够很容易地修改它,将花括号和引号放入其中。