什么是包含List<>的最佳方式作为课堂参数?

时间:2015-11-12 13:10:41

标签: c# list arraylist configuration

我有2个类,我想添加一个列表。我将使用复选框填写我的列表。但是现在我应该如何创建列表? 公共类DocPart         {             public string Title {get;组; }             public string TexLine {get;组; }         }              公共类DocConfig         {             public string说明{get;组; }             公开列表< DocPart>零件{得到;组; }                  public static DocConfig LoadFromString(string jsonData)             {                 var serializer = new DataContractJsonSerializer(typeof(DocConfig));                      var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));                 var config =(DocConfig)serializer.ReadObject(ms);                      return config;             }                  public string SaveToString()             {                 var serializer = new DataContractJsonSerializer(typeof(DocConfig));                 var ms = new MemoryStream();                 serializer.WriteObject(ms,this);                 return Encoding.UTF8.GetString(ms.ToArray());             }         } 我想在开始时为2个项目创建列表。我在考虑这段代码:  var doc = new DocConfig(); doc.Description =" bla bla&#34 ;; 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}"}); 我该怎么做? 编辑: 另外如何在控制台应用程序中显示列表记录? 编辑: 也许我在我的代码中犯了错误: 公共类DocConfig     {         public string说明{get;组; }         公开列表< DocPart>零件{得到;组; }         DocConfig()         {             var doc = new DocConfig();             doc.Description =" bla bla&#34 ;;             doc.Parts.Add(new DocPart {Title =" aaa",TexLine = @" \ include {aaa.tex}"});             doc.Parts.Add(new DocPart {Title =" bbb",TexLine = @" \ include {bbb.tex}"});             this.Parts =新列表< DocPart>()                 foreach(doc.Parts中的部分内容)                        {                 Console.WriteLine(part.Title);                      }         }

1 个答案:

答案 0 :(得分:1)

添加到您的DocConfig类:

          DocConfig()
          {
               this.Parts= new List<DocPart>();
          }  

并删除

doc.Parts = new List<DocPart>();

还阅读了constructors,其他人也没问题。

  

编辑:

要在控制台中检查列表,您可以使用foreach循环,这是与List一起使用的最佳选择:

foreach (var part in doc.Parts)
        {
            Console.WriteLine(part.Title);
        }