C# 重写 List<T> 添加方法来检查列表是否为空

我想弄清楚这是否可行/正确的语法使其工作。我想null在属性级别添加新项目时对我的列表进行检查,而不是null每次向列表添加项目时都进行检查。例如:


MyClass someClass = new MyClass()

{

    MyClassID = 1,

    Notes = null

};


//

//


Note newNote = new Note()

{

    NoteID = 1,

    Text = "Test note"

};


someClass.Notes.Add(newNote); // This line will throw an error because 

                              //      someClass.Notes is null

我想通过执行以下代码来解决这个问题。但是,我不知道是否/什么语法可以实现这一点。


public class MyClass

{

    public int MyClassID { get; set; }

    public List<Note> Notes

    {

        get; set;


        public void Add(Note note)

        {

            if (this.Notes == null)

                this.Notes = new List<Note>();


            this.Notes.Add(note);

        }

    }

}


public class Note

{

    public int NoteID { get; set; }

    public string Text { get; set; }

}

** 我知道我可以在执行之前进行空检查someClass.Notes == null并将其分配给,但我想在属性级别执行此操作,这样我就不必每次需要添加时都复制这两行代码新笔记。new List<Note>().Add(newNote)


白板的微信
浏览 120回答 2
2回答

holdtom

最好在构造函数中初始化列表MyClasspublic class MyClass{&nbsp; &nbsp; public MyClass()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Notes = new List<Note>();&nbsp; &nbsp; }}

qq_遁去的一_1

让我们介绍一下支持字段 private List<Note> m_Notes:public class MyClass{&nbsp; &nbsp; public int MyClassID { get; set; }&nbsp;&nbsp; &nbsp; // Empty list by default&nbsp; &nbsp; private List<Note> m_Notes = new List<Note>();&nbsp; &nbsp; public List<Note> Notes&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return m_Notes;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; set // If you really want "set" in the context&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Assign empty list if value is null&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_Notes = value ?? new List<Note>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP