在C#中使用什么数据类型?

Bab*_*aev -1 c# c#-4.0

我需要按键在数组中保存一些值,例如:

var arr = ['N' => 1, 'M' => 2, 'P' => 3];
Run Code Online (Sandbox Code Playgroud)

我需要在C#中使用哪种数据类型?我尝试过ArrayList类,但是它做了一个简单的数组.

Vla*_*lad 8

你想用一个Dictionary.

完整的例子:

using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var arr = new Dictionary<char, int> {
            {'N', 1},
            {'M', 2},
            {'P', 3},
        };

        foreach (var pair in arr) {
            System.Console.WriteLine(pair.Key + ": " + pair.Value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*vid 5

一个IDictionary<string, int>应该做的伎俩.就像是:

var arr = new Dictionary<string, int>
{
    { "N", 1 },
    { "M", 2 },
    { "P", 3 }
};
Run Code Online (Sandbox Code Playgroud)

(或者甚至是IDictionary<char, int>这些值应该char代替string.)

  • 您还需要导入.[`using System.Collections.Generic;`](https://msdn.microsoft.com/en-us/library/system.collections.generic(v = vs.110).aspx) (3认同)