Add element to null (empty) List<T> Property

This question already has an answer here:

  • What is a NullReferenceException, and how do I fix it? 33 answers

  • Initialize the list in the constructor:

    class Maps
    {
        public Maps()
        {
            AllAntsAtMap = new List<Ant>();
        }
    
        ...
    }
    

    (Since the property is declared in the superclass Maps, I'd do the initialization there rather than in the subclass Quadrangle.)


    You should initialize AllAntsAtMap before usage. You can use the constructor for that:

    public Quadrangle()
    {
        AllAntsAtMap = new List<Ant>();
    }
    

    在C#6中它更简单:

    protected List<Ant> AllAntsAtMap { get; set; } = new List<Ant>();
    
    链接地址: http://www.djcxy.com/p/28046.html

    上一篇: 检查datagridview单元格是否为空或空

    下一篇: 将元素添加到null(空)List <T>属性