c# - 如何创建包含一个字符串变量和三个 int 变量的字典

标签 c# dictionary integer

我正在尝试编写一些代码,将名称和记录集保存到文本文件中,并且能够读取和编辑。我决定处理这个问题的最佳方法是创建一个字典,将字符串变量作为键,将三个 int 变量作为其值。但是,我无法让特定的代码起作用。它说它不能容纳三个值,尽管它被声明为一个列表。我已附上下面的代码片段。它说错误发生在字典的 {playerwins, Computerwins, ties} 部分。

private void FileWriter(string playername, int playerwins, int computerwins, int ties)
        {
            Dictionary<string, List<int>> records = new Dictionary<string, List<int>>()
            {
                {playername, {playerwins, computerwins, ties } };
        }

最佳答案

您不能像这样使用集合初始值设定项,您需要指定实际的列表类型

new List<int>() {playerwins, computerwins, ties}

固定示例

private void FileWriter(string playername, int playerwins, int computerwins, int ties)
{
   var records = new Dictionary<string, List<int>>
   {
      {playername, new List<int>() {playerwins, computerwins, ties}}
   };
}

另一种选择是使用命名的ValueTuple

var records = new Dictionary<string, (int playerwins, int computerwins, int ties)>
{
   {playername, (playerwins, computerwins, ties)}
};

关于c# - 如何创建包含一个字符串变量和三个 int 变量的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65260814/

相关文章:

c# - 获取图像的大小

c# - standardoutput 在流 C# 的末尾暂停循环

python - 如何将字典中的嵌套 numpy 数组转换为 JSON?

c++ - MySQL 和 Sparksee 数据库中的自定义大小整数

c++ - Qt SQL : how to differentiate between a double and an int?

c# - 在 ASP.NET MVC 中编写 XML 文件?

c# - 我可以在 LINQ 语句中包含方法调用吗?

javascript - Redux Spread 运算符与 Map

python - 如何根据字典值只打印一定范围内的字典键值?

c++ - modf 返回 1 作为小数 :