简体   繁体   English

在c#中启动集合,类似于Java匿名类语法

[英]Initiate collection in c# similar to Java anonymous class syntax

In Java we can initialize an ArrayList and HashMap with anonymous class declaration syntax as follows 在Java中,我们可以使用匿名类声明语法初始化ArrayList和HashMap,如下所示

public static final List<HashMap<String,String>> data
 = new ArrayList<HashMap<String,String>>(){
{
 add(
  new HashMap<String, String>()
    {{ 
      put("name", "My Name");
      put("alias", "My Name");
    }}
  );
};

Can we do the same in C#? 我们可以在C#中做同样的事情吗? in latest windows 10 programming? 在最新的Windows 10编程中?

Collection initialization is also a feature of C#. 集合初始化也是C#的功能。 The syntax to initiate a collection in C# 4.0 is similar to that you have shown. 在C#4.0中启动集合的语法与您所显示的相似。

private static List<Dictionary<string, string>> data = 
    new List<Dictionary<string,string>>()
    {

        new Dictionary<string, string>()
            {
                { "name", "My Name" },
                {"alias", "My Name" }
            },
        new Dictionary<string, string>()
            {
                { "name2", "My Name2" },
                {"alias2", "My Name2" }
            }   
    };

For more, please consult the feature's documentation . 有关更多信息,请查阅功能文档 ( Click here for the documentation specific to C# 4.0/Visual Studio 2010.) 单击此处可获取特定于C#4.0 / Visual Studio 2010的文档。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM