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

本文关键字:字符串 数组 声明 索引 何用 | 更新日期: 2023-09-27 18:02:02

在我的代码中,我这样声明:

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;

MSDN文档

在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
    }