简体   繁体   English

在字典中访问字典的键和值

[英]Accessing key and values of a dictionary within a dictionary

I have the following file:我有以下文件:

{ "Ti": 12,
    "IES": false,
    "End": {
        "ABC": "test1",
        "XYZ": "test2",
        "QWE": "test3"
    }

and I have the following C# code that is getting these values through a class:我有以下 C# 代码,它通过 class 获取这些值:

foreach (var prop in _ABC.GetType().GetProperties())
        {
            _dic.Add(prop.Name, _ABC.GetType().GetProperty(prop.Name).GetValue(_ABC, null).ToString());
        }

This does not give me the values/keys of the dictionary within the existing dictionary.这不会给我现有字典中字典的值/键。 The class ABC looks like following: class ABC 如下所示:

   public class ABC
{
    public string Ti { get; set; }
    public string IES { get; set; }
    public End End { get; set; }
    
}

public class END
{
    public string ABC { get; set; }
    public string XYZ { get; set; }
    public string QWE { get; set; }
}

How can I get the loop to go further in to access the values of .END class我怎样才能使循环进一步进入 go 以访问.END class 的值

You could try deserializing the contents.您可以尝试反序列化内容。 It's much more robust and less error prone.它更健壮,更不容易出错。

--EDITED-- --编辑--

Change some types:改变一些类型:

  • Ti from string to int Tistringint
  • IES from string to bool IESstringbool
  • End from END to Dictionary<string, string>EndDictionary<string, string> END

public class ABC
{
    public int Ti { get; set; }
    public bool IES { get; set; }
    public Dictionary<string, string> End { get; set; }
}

The deserializing code:反序列化代码:

using System.Collections.Generic;
using System.Text.Json;

//[...]

var fileContent = @"{ ""Ti"": 12,
    ""IES"": false,
    ""End"": {
        ""ABC"": ""test1"",
        ""XYZ"": ""test2"",
        ""QWE"": ""test3""
    }
}";

var abc = JsonSerializer.Deserialize<ABC>(fileContent);
    
Console.WriteLine($"Ti: {abc.Ti}");
Console.WriteLine($"IES: {abc.IES}");
foreach (var key in abc.End.Keys)
{
    Console.WriteLine($"End.{key}: {abc.End[key]}");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM