空对象引用错误

时间:2015-04-29 07:39:00

标签: c# asp.net object reference nullreferenceexception

我创建了一个类如下

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; }
}

当我尝试像下面这样使用它时,我得到一个空对象引用错误。

Table tb3 = new Table();
tb3.Parameters.Add(new TableParameter() { ParameterName = Table.ColumnNames.ID, Value = 1, Tip = Types.INT });
希望你能帮助我。我会等你的回答。

3 个答案:

答案 0 :(得分:4)

您需要初始化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 });

或者您可以在Table类构造函数本身中初始化,如下所示

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

答案 1 :(得分:2)

您永远不会初始化Parameters。尝试在类Table的构造函数中初始化public class Table { public Table() { Parameters = new List<TableParameter>(); } public enum ColumnNames { ID, TabloName, Active, Date } public List<TableParameter> Parameters { get; set; } } 属性。

<?php
$lastDate = '';

while($row = > $played){

$gameDate = $row['event_date'];
$team1 = $row['team1'];
$team2 = $row['team2'];
$venue = $row['venue'];
$eventId = $row['event_id'];
if($gameDate !== $lastDate) {
echo'<tr>';
  $lastDate = $gamedate;
  echo $echoed ='<td>Today,'.$gameDate.'echo</td>';
echo'</tr>';
}
echo'<tr>';
echo'<td>'.$team1.'</td>';
echo'<td>'.$team2.'</td>';
echo'<td>'.$venue.'</td>';

答案 2 :(得分:0)

谢谢。我更新了我的代码,如下所示;

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

    public List<TableParameter> Parameters;

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