首页 > 解决方案 > 如何获取对象的键作为键值对?

问题描述

我有类对象,我需要以特定格式存储它的值和键。

public class AppSettings
{
    public int TokenLifeTime { get; set; } = 450;

    public List<string> Urls { get; set; } = new List<string>
    {
        "www.google.com",
        "www.hotmail.com"
    };

    public List<ServersList> ServersList { get; set; } = new List<ServersList>
    {
        new ServersList {IsHttpsAllowed = false},
        new ServersList {IsHttpsAllowed = true}
    };
}

public class ServersList
{
    public bool IsHttpsAllowed { get; set; }
}

我想获得这种格式的密钥。

"AppSettings:TokenLifeTime" , 450
"AppSettings:Urls:0", "www.google.com"
"AppSettings:Urls:1", "www.hotmail.com"
"AppSettings:ServersList:0:IsHttpsAllowed", false
"AppSettings:ServersList:1:IsHttpsAllowed", true

无论对象深度如何,有什么方法可以递归地将所有键作为字符串。上面的代码只是一个实际情况的例子,我有很长的列表和更多的数据。

标签: c#.net-core

解决方案


我不认为有什么开箱即用的。

您需要自己创建一些东西并定义您的规则。

以更原始的形式,我将从以下开始:

      Type t = typeof(AppSettings);
      Console.WriteLine("The {0} type has the following properties: ",
                        t.Name);
      foreach (var prop in t.GetProperties())
         Console.WriteLine("   {0} ({1})", prop.Name,
                           prop.PropertyType.Name);

IEnumerable然后为对象和原始值类型添加一个规则以在迭代等中处理它们。


推荐阅读