【问题标题】:NullReferenceException when using MyListProperty.Add?使用 MyListProperty.Add 时出现 NullReferenceException?
【发布时间】:2012-06-25 21:03:28
【问题描述】:
 public List<string> myitems { get; set; }
    //Store All unique ID of this date in a list
    public void myitem(string Index)
    {
        myitems.Add(Index);
    }

  if (temp.Start == received)
            {

                scheduledItem scheduleditem = new scheduledItem(temp.Name, "1pm", "true");
                DataCollection.Add(scheduleditem);
                myitem(temp.UniqueID.ToString()); 
            }
            else
            {
                MessageBox.Show("Nothing");

            }

知道 myitems.add(index) 出了什么问题; ?

【问题讨论】:

  • new List&lt;string&gt; 在哪里?它将解释null(“缺少对象”)..

标签: c# nullreferenceexception


【解决方案1】:

您必须实例化/初始化List&lt;T&gt;

 private List<string> _list = new List<string>();

 public List<string> myitems 
 { 
     get { return _list; }
 }

【讨论】:

    【解决方案2】:

    您实际上还没有初始化 myitems。你需要在某处添加这行代码,比如你的类的构造函数

    myitems = new List<string>();
    

    【讨论】:

    • 哦!好的,我开始明白初始化谢谢的意思了!
    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2018-04-02
    • 2011-11-01
    相关资源
    最近更新 更多