如何获取对象的键作为键值对?

时间:2020-02-11 05:21:23

标签: c# .net-core

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

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

有没有办法以递归方式将所有键作为字符串获取而与对象深度无关。上面的代码只是一个例子,在实际情况下,我的清单很长,数据很多。

2 个答案:

答案 0 :(得分:1)

我认为没有任何现成的东西。

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

在更原始的形式中,我将从以下内容开始:

      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添加一条规则,以对对象和原始值类型进行迭代等等。

答案 1 :(得分:0)

我为您提供了两个示例:

选项1:

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

    public Dictionary<string, ServersList> Urls { get; set; } = new Dictionary<string, ServersList>
    {
        {"www.google.com", new ServersList {IsHttpsAllowed = false}},
        { "www.hotmail.com", new ServersList {IsHttpsAllowed = true}}

    };
}

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

此选项会将值分组在一起,但是您将丢失基于“ int”的索引。不确定这是否重要。

选项2:

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

    public List<KeyValuePair<string, ServersList>> Urls { get; set; } = new List<KeyValuePair<string, ServersList>>
    {
        new KeyValuePair<string, ServersList>("www.google.com",new ServersList {IsHttpsAllowed = false}),
        new KeyValuePair<string, ServersList>("www.hotmail.com", new ServersList {IsHttpsAllowed = true})
    };

    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; }
}

此选项将保留基于“ int”的索引,并且值仍被分组。但是感觉笨拙...

选项3 :(我会选择的那个)

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

    public List<Server> ServersList { get; set; } = new List<Server>
    {
        new Server { Url = "www.google.com", IsHttpsAllowed = false},
        new Server { Url = "www.hotmail.com", IsHttpsAllowed = true}
    };
}

public class Server
{
    public string Url { get; set; }
    public bool IsHttpsAllowed { get; set; }
}

此选项仍然为您提供基于“ int”的索引,并将数据分组在一起(这应该来自示例中的理解)。