【问题标题】:How to add more items to my list如何将更多项目添加到我的列表中
【发布时间】:2015-11-13 11:27:37
【问题描述】:

我已经创建了列表。它只编译并显示一项。我需要让它显示我所有插入的项目。例如,我尝试再插入一个。我该怎么做?

    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;
                }

            }
        }
    }

【问题讨论】:

  • 删除return 0
  • 为什么 Main 方法应该返回任意数字?
  • 虽然您的程序很短,但您还应该尝试将问题中包含的代码的 sn-ps 范围缩小到所需的最短必要代码,在这种情况下应该是 @987654323 @ 方法本身。

标签: c# list foreach


【解决方案1】:

它只显示一个的原因是因为您对部件的循环是从方法返回的,因此它永远没有机会完成任何其他迭代。

解决方法是不要从这个方法中提前返回(删除return 0;),而是让它运行到最后。

我在下面所做的其他一些更改是:

  • 从 for 循环中删除了读取键。您可能也不希望用户每次迭代都必须按一个键。
  • 非嵌套类。你的嵌套类在我看来也很奇怪,只会把你带到混乱的代码中。
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;
        }

    }
}

【讨论】:

  • return -1 对我来说似乎比嵌套类更奇怪,那可能没用。我认为 OP 有复制粘贴代码,所以他真的不知道发生了什么。
  • @M.kazemAkhgary - 这是在their last question 中向 OP 提出的建议,所以我不想将它们与相互矛盾的答案混淆。我同意在这里返回 0 可能更好
猜你喜欢
  • 2022-10-25
  • 2019-11-26
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-04-04
相关资源
最近更新 更多