我可以使用字典℃的集合初始化; TKEY的,TValue>项? [英] Can I use a collection initializer for Dictionary<TKey, TValue> entries?

查看:94
本文介绍了我可以使用字典℃的集合初始化; TKEY的,TValue>项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个集合初始化为code下位:

 公共字典< INT,字符串> GetNames()
{
    字典< INT,字符串>名称=新词典< INT,字符串>();
    names.Add(1,亚当);
    names.Add(2,巴特);
    names.Add(3,查理);
    返回名称;
}
 

所以通常它应该是这样的:

 返回新字典< INT,字符串>
{
   1,亚当,
   2,巴特
   ...
 

但是,什么是正确的语法呢?

解决方案

  VAR名称=新词典< INT,字符串> {
  {1,亚当},
  {2,巴特},
  {3,查理}
};
 

I want to use a collection initializer for the next bit of code:

public Dictionary<int, string> GetNames()
{
    Dictionary<int, string> names = new Dictionary<int, string>();
    names.Add(1, "Adam");
    names.Add(2, "Bart");
    names.Add(3, "Charlie");
    return names;
}

So typically it should be something like:

return new Dictionary<int, string>
{ 
   1, "Adam",
   2, "Bart"
   ...

But what is the correct syntax for this?

解决方案

var names = new Dictionary<int, string> {
  { 1, "Adam" },
  { 2, "Bart" },
  { 3, "Charlie" }
};

这篇关于我可以使用字典℃的集合初始化; TKEY的,TValue&GT;项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆