[英]How to declare array of strings with string index?
在我的代码中我声明如下:
public string[] s ;
我需要像这样使用这个字符串:
s["Matthew"]="Has a dog";
s["John"]="Has a car";
当我使用s [“Matthew”]时会出现错误并且显示“无法将'string'隐式转换为'int'”。 如何使字符串数组具有字符串索引? 如果我在php中写这个有效:
array() a;
a["Mathew"]="Is a boy";
我还需要它在asp.net中工作!
public Dictionary<string, string> s;
在C#中,您不能使用字符串作为数组索引来访问数组元素。 出于这个原因,你有一个转换错误,因为根据数组的定义,数组的索引是一个整数。
为什么不使用像字典这样的数据结构?
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"]);
数组工作索引和索引是数字但你传递的字符串,这就是你得到错误的原因,@ 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.