You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现嵌套字典?求将Python嵌套字典代码转译为C#

在C#中实现等效的嵌套字典结构

先看你提供的Python原代码:

T_DICT = {
       "ABC_Table":
           {
             "table": "ABC",
             "schema": "XYZ",
             "columns": 
                 { 
                   'Id': {"type": 'bigint', "name": "[ID]", 'IsIden': True, 'IsNull': False},
                   'T_ID': {"type": 'bigint', "name": "Tsa", 'IsIden': False, 'IsNull': False},
                 }
           }
         }

下面提供两种C#实现方式:

1. 使用嵌套的Dictionary<string, object>(快速原型实现)

这种方式和Python字典结构最接近,无需额外定义类,但缺乏类型安全,访问值时需要强制转换:

var T_DICT = new Dictionary<string, object>
{
    ["ABC_Table"] = new Dictionary<string, object>
    {
        ["table"] = "ABC",
        ["schema"] = "XYZ",
        ["columns"] = new Dictionary<string, object>
        {
            ["Id"] = new Dictionary<string, object>
            {
                ["type"] = "bigint",
                ["name"] = "[ID]",
                ["IsIden"] = true,
                ["IsNull"] = false
            },
            ["T_ID"] = new Dictionary<string, object>
            {
                ["type"] = "bigint",
                ["name"] = "Tsa",
                ["IsIden"] = false,
                ["IsNull"] = false
            }
        }
    }
};

访问示例(获取Id列的IsIden属性):

var columns = (Dictionary<string, object>)((Dictionary<string, object>)T_DICT["ABC_Table"])["columns"];
var idColumn = (Dictionary<string, object>)columns["Id"];
bool isIden = (bool)idColumn["IsIden"];

2. 定义强类型类(推荐,类型安全)

通过自定义类映射结构,编译时就能检查类型错误,可读性和维护性更好:

先定义对应的数据类:

public class ColumnInfo
{
    public string Type { get; set; }
    public string Name { get; set; }
    public bool IsIden { get; set; }
    public bool IsNull { get; set; }
}

public class TableInfo
{
    public string Table { get; set; }
    public string Schema { get; set; }
    public Dictionary<string, ColumnInfo> Columns { get; set; }
}

然后初始化字典:

var T_DICT = new Dictionary<string, TableInfo>
{
    ["ABC_Table"] = new TableInfo
    {
        Table = "ABC",
        Schema = "XYZ",
        Columns = new Dictionary<string, ColumnInfo>
        {
            ["Id"] = new ColumnInfo
            {
                Type = "bigint",
                Name = "[ID]",
                IsIden = true,
                IsNull = false
            },
            ["T_ID"] = new ColumnInfo
            {
                Type = "bigint",
                Name = "Tsa",
                IsIden = false,
                IsNull = false
            }
        }
    }
};

访问示例(直接通过属性获取):

bool isIden = T_DICT["ABC_Table"].Columns["Id"].IsIden;

内容的提问来源于stack exchange,提问作者TEJAS KACHARE

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 19:30:49