如何将IList与主/详细类型类一起使用?

时间:2011-06-13 18:32:33

标签: c#

我试过了:

public class TextFillerParent
    {

   /////// I am not sure if the code on the next 7 lines is correct ///////
        public IList<TextFillerDetail> TextFillerDetails
        {
            get { return _textfillerDetails; }
            set { _textfillerDetails = new List<TextFiller>(value); }
        }

        private List<TextFiller> _textfillerDetails;
    }

    public class TextFillerDetail
    {

        public TextFillerDetail()
        {
            this.Text = new HtmlText();
            this.ImageFile = String.Empty;
        }

        public HtmlText Text { get; set; }
        public string ImageFile { get; set; }
    }

    public class HtmlText
    {

        public HtmlText()
        {
            TextWithHtml = String.Empty;
        }
        [AllowHtml]
        public string TextWithHtml { get; set; }
    }

然后:

        var txt = new TextFillerParent();

  txt.TextFillerDetails.Add(new TextFillerDetail()); <<<<<<<<<<<<<<<<<<<<<<
  txt.TextFillerDetails.Add(new TextFillerDetail
  {
      Text = new HtmlText { TextWithHtml = "One" },
      Explanation = new HtmlText { TextWithHtml = "One" }
  });
  txt.TextFillerDetails.Add(new TextFillerDetail
  {
      Text = new HtmlText { TextWithHtml = "Two" },
      Explanation = new HtmlText { TextWithHtml = "Two" }
  });

  var abb = txt.TextFillerDetails[1];

我认为缺少某些东西或者我做错了什么。当我运行代码时,我得到一个错误消息=对象引用未设置为对象的实例。在&lt;&lt;&lt;&lt;&lt;

的行上

1 个答案:

答案 0 :(得分:2)

您拥有它的方式,您从未将TextFillerDetails设置为新列表。 您只应为_textfillerDetails创建一次新列表:

public IList<TextFillerDetail> TextFillerDetails        
{            
    get { return _textfillerDetails; }
}        

private List<TextFiller> _textfillerDetails = new List<TextFiller>();