簡體   English   中英

如何使用字符串索引聲明字符串數組?

[英]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;

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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM