Set array key as string not int?

前端 未结 6 1055
耶瑟儿~
耶瑟儿~ 2020-12-03 06:58

I am trying to set the array keys as a strings like in the example below, but inC#.



        
6条回答
  •  佛祖请我去吃肉
    2020-12-03 07:26

    The closest you get in C# is Dictionary:

    var dict = new Dictionary();
    dict["key_name"] = "value1";
    

    Note that a Dictionary is not the same as PHP's associative array, because it is only accessible by one type of key (TKey -- which is string in the above example), as opposed to a combination of string/integer keys (thanks to Pavel for clarifying this point).

    That said, I've never heard a .NET developer complain about that.


    In response to your comment:

    // The number of elements in headersSplit will be the number of ':' characters
    // in line + 1.
    string[] headersSplit = line.Split(':');
    
    string hname = headersSplit[0];
    
    // If you are getting an IndexOutOfRangeException here, it is because your
    // headersSplit array has only one element. This tells me that line does not
    // contain a ':' character.
    string hvalue = headersSplit[1];
    

提交回复
热议问题