简体   繁体   中英

Does C# have array with index is a string like PHP?

I have been learning C# myself for 2 months. Before, I learned PHP and see that it has an array where the index is a string, like this:

$John["age"] = 21;
$John["location"] = "Vietnam";

It is very useful to remember what we set to an array element. I tried to find if C# supports that array type, but I haven't seen any answers, yet.

Does C# have an array like this? If it does, how can I create it?

C# supports any type of object for an index. A baked-in implementation is System.Collections.Generic.Dictionary<T1,T2> . You can declare one like this:

Dictionary<string, string> myDictionary = new Dictionary<string, string>();

Yes, this is an associative array, represented in C# by the generic Dictionary<TKey, TValue> class or the non-generic Hashtable .

Your code would be only possible with a Hashmap as the values are not all of the same type. However, I strongly suggest you re-think that design.

Use a System.Collections.Generic.Dictionary<T1,T2> as other said. To complete your knowledge, you should know that you can control yourself the behavior of the [] . Exemple :

public class MyClass
{
    public string this[string someArg]
    {
        get { return "You called this with " + someArg; }
    }

}

class Program
{

    void Main()
    {
        MyClass x = new MyClass();
        Console.WriteLine(x["something"]);
    }
}

Will produce "You called this with something".

More on this in the documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM