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

问题描述

| 我试过了:
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];
我认为缺少某些内容或做错了什么。当我运行代码时,出现错误Message = Object引用未设置为对象的实例。与<<<<     

解决方法

        使用它的方式,您从未将TextFillerDetails设置为新列表。 您应该只为_textfillerDetails创建新列表:
public IList<TextFillerDetail> TextFillerDetails        
{            
    get { return _textfillerDetails; }
}        

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