簡體   English   中英

C#:為任何給定字符串設置 integer

[英]C#: Set integer for any given string

我想列出我每次升級的費用。

例子:

字符串:“更快的射擊”,int:10

我想要一種簡單的方法來為長列表中的任何字符串設置特定的 int,然后通過字符串獲取 int

使用Dictionary<TKey,TValue> ,它是鍵值對的集合。 在這種情況下,您的鍵將是一個string ,您的值是一個int

var dict = new Dictionary<string, int>();
dict["Faster Shooting"] = 10; // add "Faster Shooting" key, set to value 10.
dict["Faster Shooting"] = 15; // update "Faster Shooting" key, set to value 15.
Console.WriteLine(dict["Faster Shooting"]); // print "Faster Shooting" value

它還公開了Add()TryAdd()和其他方便的方法,有關使用Add()的替代方法,請參閱@Heinzi 的答案

我想要一種簡單的方法來為長列表中的任何 Y 設置特定的 X,然后通過 Y 獲取 X。

There's a built-in .NET data structure for exactly this purpose: A dictionary (sometimes called map , hash map or associative array in other programming languages).

代碼示例:

var dic = new Dictionary<string, int>();
dic.Add("Foo", 3);
dic.Add("Bar", 4);

Console.WriteLine(dic["Foo"]); // prints 3

更多示例可以在文檔中找到。

暫無
暫無

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

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