doutuo8800 2019-04-06 21:54
浏览 177
已采纳

从php到c#:字典数组,或字典词典?

I'm a newbie at programming. I have this php code, it's basically used for translating some sentences from txt files:

$LANG = array();

$LANG['en'] = array(
    11 => "Name",
    20 => "Surname",
    21 => "Age",
    22 => "Profession",
);
$LANG['es'] = array(
    11 => "Nombre",
    20 => "Apellido",
    21 => "Edad",
    22 => "Profesión",
);

I'm trying to do the same in c#, something like this:

Dictionary<int, string>[] LANG = new Dictionary<int, string>[]
        {
        new Dictionary<int, string>(),
        LANG['en']=new Dictionary<int, string>()
             {
                 {11, "Name"},
                 {20, "Surname"},
                 {21, "Age"},
                 {22, "Profession"}
             },
        LANG['es']=new Dictionary<int, string>()
             {
                 {11, "Nombre"},
                 {20, "Apellido"},
                 {21, "Edad"},
                 {22, "Profesión"}
             }
        };

1) Is this c# doing exactly the same as the php code? Should i do an array of dictionaries, or should i do a dictionary of dictionaries?

2) For LANG['en'] and LANG['es'], i'm getting the error message "A field initializer cannot reference the non-static field, method or property 'Form1.LANG'. What am i doing wrong?

  • 写回答

1条回答 默认 最新

  • dongzhang0243 2019-04-06 22:37
    关注

    1) Yes. PHP associative array equivalent in C# would be a Dictionary. Array in C# doesn't support non-integer indexes so you need to use Dictionary with string key and therefore you'll have to use dictionary of dictionaries.

    2) Apparently the syntax is invalid. To turn your PHP code into C# do the following

    //instantiate dictionary of dictionaries
    var LANG = new Dictionary<string, Dictionary<int, string>>();
    
    //set dictionary for "en" key
    LANG["en"] = new Dictionary<int, string>()
    {
        { 11, "Name" },
        { 20, "Surname" },
        { 21, "Age" },
        { 22, "Profession" }
    };
    
    //set dictionary for "es" key
    LANG["es"] = new Dictionary<int, string>()
    {
        { 11, "Nombre" },
        { 20, "Apellido" },
        { 21, "Edad" },
        { 22, "Profesión" }
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器