【问题标题】:Define a List of Objects in C#在 C# 中定义对象列表
【发布时间】:2015-02-11 10:45:28
【问题描述】:

我有一个 C# 控制台应用程序。我的应用程序有一个名为 Item 的类。项目定义如下:

public class Item {
  public int Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
}

我想建立一个List<Item> items;在我看来,C# 有一种在运行时定义列表的简写方式。比如:

List<Item> items = new List()
  .Add(new Item({ Id=1, Name="Ball", Description="Hello" })
  .Add(new Item({ Id=2, Name="Hat", Description="Test" });

现在我似乎找不到像我提到的那样的简写语法。我在做梦吗?或者有没有一种简单的方法来建立一个集合列表?

谢谢!

【问题讨论】:

    标签: c#


    【解决方案1】:

    您可以像这样使用object &amp; collection initializer(C# 3.0 及更高版本):

    List<Item> items = new List<Item>
    {
       new Item { Id=1, Name="Ball", Description="Hello" },
       new Item { Id=2, Name="Hat", Description="Test" }
    };
    

    【讨论】:

      【解决方案2】:

      有。语法是这样的:

      List<Item> items = new List<Item>()
      {
          new Item{ Id=1, Name="Ball", Description="Hello" },
          new Item{ Id=2, Name="Hat", Description="Test" }
      }
      

      【讨论】:

        【解决方案3】:

        在我看来,Amir popovich 的回答是正确的,这就是应该的方式......

        但如果我们想声明与您在问题中提到的相同的列表:

        List<Item> items = new List()
          .Add(new Item({ Id=1, Name="Ball", Description="Hello" })
          .Add(new Item({ Id=2, Name="Hat", Description="Test" });
        

        你可以编写一个扩展方法来实现你想要的

        检查此代码(小型控制台应用程序)

        using System;
        using System.Collections.Generic;
        
        public class Program
        {
            public static void Main()
            {
                List<Item> items = new List<Item>()
                    .AddAlso(new Item{ Id=1, Name="Ball", Description="Hello" })
                    .AddAlso(new Item{ Id=2, Name="Hat", Description="Test" });
        
                foreach(var item in items)
                    Console.WriteLine("Id {0} Name {1}, Description {2}",item.Id,item.Name,item.Description);
            }
        }
        
        public static class Extensions
        {
            public static List<T> AddAlso<T>(this List<T> list,T item)
            {
                list.Add(item);
                return list;
            }
        }
        
        public class Item
        {
            public int Id{get;set;}
            public string Name{get;set;}
            public string Description{get;set;}
        }
        

        这里有一个工作的DEMO

        【讨论】:

          【解决方案4】:

          我会这样做:

          var items = new List<Item>
          {
             new Item { Id=1, Name="Ball", Description="Hello" },
             new Item { Id=2, Name="Hat", Description="Test" }
          };
          

          Here 是详细信息。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2013-05-06
            • 2020-11-19
            • 2011-02-07
            • 2021-07-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多