简体   繁体   English

如何使用字符串索引声明字符串数组?

[英]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'" . 当我使用s [“Matthew”]时会出现错误并且显示“无法将'string'隐式转换为'int'”。 How can I make a string array to have string index ? 如何使字符串数组具有字符串索引? if i write this in php it works : 如果我在php中写这个有效:

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

I need it to work also in asp.net ! 我还需要它在asp.net中工作!

public Dictionary<string, string> s;

MSDN文档

In C#, you cannot access an array element using, as array index, a string. 在C#中,您不能使用字符串作为数组索引来访问数组元素。 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 数组工作索引和索引是数字但你传递的字符串,这就是你得到错误的原因,@ Christian建议你使用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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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