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 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起