问题
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