【发布时间】:2017-04-20 02:14:58
【问题描述】:
我有一个导致堆栈溢出异常的代码的简单示例,我想知道这是一个常见问题还是某种错误。
我正在使用控制台应用程序来生成一些数据。它将大约 20000 个对象添加到集合中。有些字段可以为空。如果我让他们布尔?那么它可以工作,但如果我将其中几个(如我在示例代码中所做的那样)更改为十进制?然后它抛出异常。
它也只在我物理添加 20000 Add(... 行时才会这样做。如果我在循环中这样做,那么它工作正常(这也在示例中)。
对代码示例的长度表示歉意。任何帮助将不胜感激。
using System.Collections.Generic;
using System;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"{new UpdateCommands().Count} commands");
Console.WriteLine($"{new CreateCommands().Count} commands");
Console.ReadKey();
}
}
}
public class CreateCommand
{
public CreateCommand(string code, string name, string label, string field1, string field2, string field3,
bool? field4, bool? field5, bool? field6, bool? field7, decimal? field8, decimal? field9, decimal? field10, decimal? field11)
{
}
}
public class UpdateCommands : List<CreateCommand>
{
public UpdateCommands()
{
for (int i = 0; i < 22000; i++)
{
Add(new CreateCommand("code", "name", "label", "", null, null, null, null, null, null, null, null, null, null));
}
}
}
public class CreateCommands : List<CreateCommand>
{
public CreateCommands()
{
Add(new CreateCommand("code", "name", "label", "", null, null, null, null, null, null, null, null, null, null));
you need to copy the line above 22000 times
}
}
【问题讨论】:
-
那不会编译,因为没有
CreateCommands类。如果您的意思是new CreateCommand没有无参数构造函数,也没有定义Count方法。 -
我认为问题的目的是关于为什么当有很多行时你会得到stackoverflow。这不是愚蠢的问题。因为 OP 已经知道如何使用循环,这是出于学习目的。
-
我刚刚对此进行了测试,
Main方法中的第一行运行良好。第二个无法编译,因此您需要提供更多信息才能弄清楚发生了什么。 -
@juharr 它确实有一个无参数的构造函数。它有
Count,因为它继承自基类。 -
@Servy 我说的是
new CreateCommands()的第二行。
标签: c# .net collections stack overflow