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 echarts绘制图表
  • ¥15 根据企业名称 对照两个文件 样本筛选/匹配
  • ¥15 Linux环境下CA证书更新问题
  • ¥15 sqlserver语句提取结果以外数据
  • ¥60 微信小程序如何上传QQ聊天文件
  • ¥300 开发的系统遭到无良商家的破解,请问如何防止再次发生,并追回损失
  • ¥15 java代码写在记事本上后在cmd上运行时无报错但又没生成文件
  • ¥15 关于#python#的问题:在跑ldsc数据整理的时候一直抱这种错误,要么--out识别不了参数,要么--merge-alleles识别不了参数(操作系统-linux)
  • ¥15 PPOCRLabel
  • ¥15 混合键合键合机对准标识