Null Object Reference Error [duplicate]

ε祈祈猫儿з 提交于 2019-12-23 06:12:59

问题


I created a class like below

public class Table
{
   public enum ColumnNames
   {
       ID,
       TableName,
       Active,
       Date
   }

   public List<TableParameter> Parameters { get; set; }
}

public enum Types
{
    INT,
    STRING,
    DATETIME,
    BOOLEAN,
    DECIMAL
}

public class TableParameter
{
    public Table.ColumnNames ParameterName { get; set; }
    public Types? Tip { get; set; }
    public dynamic Value { get; set; }
}

When I try to use it like below, I'm getting a null object reference error.

Table tb3 = new Table();
tb3.Parameters.Add(new TableParameter() { ParameterName = Table.ColumnNames.ID, Value = 1, Tip = Types.INT });

Hope you will help me. I'll wait for your answer.


回答1:


You need to initialize tb3.Parameters

Table tb3 = new Table();
tb3.Parameters = new List<TableParameter>();
tb3.Parameters.Add(new TableParameter() { ParameterName = Table.ColumnNames.ID, Value = 1, Tip = Types.INT });

or you can initialize in Table class constructor itself like below

public class Table
{
  public Table()
  {
     Parameters = new List<TableParameter>();
  }
}



回答2:


You never initialize Parameters .Try to initialize Parameters property in constuctor of class Table.

public class Table
{
  public Table()
  {
     Parameters = new List<TableParameter>();
  }

   public enum ColumnNames
   {
       ID,
       TabloName,
       Active,
       Date
   }

   public List<TableParameter> Parameters { get; set; }
}



回答3:


Thank you. I updated my code like below;

public class Table
{
    public enum ColumnNames
    {
        ID,
        TableName,
        Active,
        Date
    }

    public List<TableParameter> Parameters;

    public Table()
    {
        Parameters = new List<TableParameter>();
    }
}


来源:https://stackoverflow.com/questions/29937258/null-object-reference-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!