【问题标题】:How to add more than 3 items to a dictionary如何在字典中添加 3 个以上的项目
【发布时间】:2021-02-17 02:39:27
【问题描述】:
Dictionary<string, string, bool> loginUserData = new Dictionary<string, string, bool>(); 
loginUserData.Add("max", "123", true);

导致此错误:

使用泛型 'Dictionary' 需要 2 个类型参数

我做错了什么?

【问题讨论】:

  • Dictionary&lt;string, string, bool&gt; 无效,至少对于框架的Dictionary 类,你的意思是Dictionary&lt;string, (string, bool)&gt;
  • 您到底想达到什么目标?字典将(一种类型的)键映射到(一种类型的)值。
  • 您可以使用元组元组docs.microsoft.com/de-de/dotnet/api/…
  • @vc74 你应该提到你指的是Tuple type(string, bool)

标签: c# dictionary nested


【解决方案1】:

字典是一个键/值集合,键只能有一种类型,值只能有另一种类型,因此对于您的情况,您可以使用元组来表示值

Dictionary<string, (string, bool)> loginUserData = new Dictionary<string, (string, bool)>(); 
loginUserData.Add("max", ("123", true));

否则,如果您不需要键来满足您的进一步需求,请尝试使用具有三个参数的元组。

【讨论】:

  • 谢谢!有用。现在,如果我想做if (!loginUserData[.ContainsKey(Console.ReadLine())) 之类的事情,我该如何访问字符串? (这是loginUserData.Add(("max", "mustermann"), false);顺便说一句
  • 首先,你的Add不正确,你应该把这个,C# loginUserData.Add("max", ("mustermann", false)), 你可以匿名访问名字C# loginUserData["max"].item1 ,也可以用named tuple代替跨度>
猜你喜欢
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
相关资源
最近更新 更多