我创建了列表。它编译并只显示一个项目。我需要让它显示我所有插入的项目。例如,我尝试再插入一个。我该怎么做?
namespace ConsoleApplication5
{
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts;
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
public class Program
{
public static int Main()
{
List<DocPart> Parts = new List<DocPart>();
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = @"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb ", TexLine = @"\include{bbb.tex}" });
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
Console.ReadLine();
Console.ReadKey();
{
return 0;
}
}
return -1;
}
}
}
}
答案 0 :(得分:1)
它只显示一个原因是因为你的循环部分从方法返回,因此它永远不会有机会完成任何其他迭代。
解决方案是不要提前返回(从这个方法中移除return 0;
),而是让它运行到最后。
我在下面做的其他一些更改是:
namespace ConsoleApplication5
{
public class DocConfig
{
public string Description { get; set; }
public List<DocPart> Parts;
}
public class DocPart
{
public string Title { get; set; }
public string TexLine { get; set; }
}
public class Program
{
public static int Main()
{
List<DocPart> Parts = new List<DocPart>();
var doc = new DocConfig();
doc.Description = "bla bla";
doc.Parts = new List<DocPart>();
doc.Parts.Add(new DocPart { Title = "aaa", TexLine = @"\include{aaa.tex}" });
doc.Parts.Add(new DocPart { Title = "bbb ", TexLine = @"\include{bbb.tex}" });
foreach (DocPart part in doc.Parts)
{
Console.WriteLine(part.Title);
}
Console.ReadKey();
return -1;
}
}
}