使用数组初始化List <t>并填充

时间:2016-07-21 12:50:10

标签: c#

我以为我很聪明,但我错了。因此,对于单元测试,我需要列表中的每个项目中的X数量列表和一些值。所以我想出了这个作为到达那里的简洁方法。

List<PlanList> planList = new List<PlanList>(new PlanList[7]);
planList.ForEach(c => c.Description = "I'm a Description");
planList.ForEach(c => c.OrderPosition = 1);

但事实证明我得到了7个空对象的列表。

enter image description here

所以我很想知道发生了什么,但更重要的是,我只是想快速生成一个包含7个对象的List,它可以为我的测试提供相同的值。

4 个答案:

答案 0 :(得分:8)

看来你正在寻找这样的东西:

List<PlanList> planList = Enumerable
  .Range(0, 7)
  .Select(index => new PlanList() {
     Description = "I'm a Description", 
     OrderPosition = 1 
   })
  .ToList();

即。 创建 7 PlanList个实例,实现它们作为列表。

答案 1 :(得分:5)

您没有在数组的每个索引处创建对象。我看不到任何new PlanList()。因此,您创建了一个长度为7的数组,其中包含参考类型PlanList的默认值NULL

您的代码应在NullReferenceExpcetion中添加ForEach

我会这样做:

List<PlanList> planList = (from index in Enumerable.Range(0, 7)
                            select new PlanList()
                            {
                                Description = "I'm a Description",
                                OrderPosition = index
                            }).ToList();

答案 2 :(得分:5)

我猜这里PlanListstruct,对吗? (没有new,并且值丢失了。)

使用struct,当您从列表中获取项目时,您有一个副本。如果你改变副本:原件不知道或不关心。

基本上,大多数问题都应该通过PlanList一个class来解决。在大多数常规C#代码中创建struct非常罕见。

请注意,您需要创建实例。如果是我,我会使用(PlanListclass):

var list = new List<PlanList>();
for(int i = 0 ; i < 7 ; i++)
    list.Add(new PlanList { Description  = "foo", OrderPosition = 1});

答案 3 :(得分:2)

创建新数组new PlanList[7]时,数组中的所有元素都将初始化为该类型的默认值(请参阅default keyword)。在您的情况下,PlanList默认值null

您必须手动初始化每个元素。

一种方法:

for(int i = 0; i < planList.Count; i++)
   planList[i] = new PlanList();