简体   繁体   中英

How to declare array of strings with string index?

In my code i declared like this :

public string[] s ;

and i need to use this string like this :

s["Matthew"]="Has a dog";
s["John"]="Has a car";

when i use s["Matthew"] an error appears and it says "Cannot implicitly convert 'string' to 'int'" . How can I make a string array to have string index ? if i write this in php it works :

array() a;
a["Mathew"]="Is a boy";

I need it to work also in asp.net !

public Dictionary<string, string> s;

MSDN文档

In C#, you cannot access an array element using, as array index, a string. For this reason you have that cast error, because the index of an array is, by definition of an array, an integer.

Why don't you use a data structure like a dictionary ?

var dict = new Dictionary<string,string>();

dict.Add("John","I am John");

//print the value stored in dictionary using the string key
Console.WriteLine(dict["John"]);

Array works on indexes and indexes are in numbers but you are passing string that's why you are getting error, @Christian suggest you to use Dictionary

    Dictionary<string, string> dict = new Dictionary<string, string>()
    {
            {"key1", "value1"},
            {"key2", "value2"},
            {"key3", "value3"}
    };

    // retrieve values:
    foreach (KeyValuePair<string, string> kvp in dict)
    {
        string key = kvp.Key;
        string val = kvp.Value;
        // do something
    }

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