c# - 如何在声明本身中初始化泛型?

标签 c# asp.net

  • 声明:

    var list = new List<KeyValuePair<int, string>>();
    
  • 作业:

    list.Add(new KeyValuePair<int, string>(1, "Cat"));
    list.Add(new KeyValuePair<int, string>(2, "Dog"));
    list.Add(new KeyValuePair<int, string>(4, "Rabbit"));
    

如何在第一行本身初始化上面的泛型列表

例如:

List<string> nameslist = new List<string>();
nameslist.Add("one");
nameslist.Add("two"); 
nameslist.Add("three");

我们可以在同一行中初始化上面的内容:

var list = new List<string> { "One", "Two", "Three" };

我想为我的通用列表做同样的事情。任何帮助将不胜感激。提前致谢。

最佳答案

如果我理解正确,请使用:

var list = new List<KeyValuePair<int, string>>
{
    new KeyValuePair<int, string>(1, "Cat"),
    new KeyValuePair<int, string>(2, "Dog"),
    new KeyValuePair<int, string>(4, "Rabbit")
};

关于c# - 如何在声明本身中初始化泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20885470/

相关文章:

c# - 在 c# (windows) 应用程序中不存在控件时显示 .gif 动画

c# - 如何在 Unity C# 中为多个游戏对象移动进行多线程处理

c# - 在 IIS7 中从 ASP.NET 调用非托管代码

c# - 什么是 ASP.net 项目中的 Servlet(在 tomcat 中扩展 HttpServlet 的 Java 类)?

c# - ASP CSS 页脚问题

c# - 单击 jqGrid 中的一行获取列的值

c# - 具有继承设计的泛型 - 需要帮助来修复

c# - 使用 AsyncTask 的 Android ListView 过滤

c# - SQL 查询未检索到正确的结果

asp.net - ListView 控件中的日期格式