未处理的异常:NullReferenceException:对象引用未设置为

时间:2014-03-05 13:26:23

标签: c# console-application nullreferenceexception object-reference

我知道我犯的是一个愚蠢的错误,但不幸的是,即使经过大量的调试,我也无法找到它。 我已经上课“naivebayes”和其他课程连接

========================这是连接的方法========== ======

  public NaiveBayes[] ReadOBj()
    {
        SqlConnection conn = new SqlConnection(connectionString);
        conn.Open();

        SqlCommand command = new SqlCommand(@"SELECT NAME, CODE, DEPARTMENT, TS, CD, REPEAT, CORE, [Content], Grade  FROM            Transcript WHERE        (Grade <> 'UNKNOWN')", conn);
        SqlDataReader reader = null;
        reader=command.ExecuteReader();
        NaiveBayes[] a=new NaiveBayes[10];
        NaiveBayes1.NaiveBayes na = new NaiveBayes();

        int i = 0;
        while (reader.Read())
        {
            i++;

                string Namee = (string)reader["NAME"];
                Console.WriteLine(Namee);
                na.Name = Namee;

            string depte=reader["DEPARTMENT"].ToString();
            na.Dept = depte;

             string core=   reader["CORE"].ToString();
            Boolean.TryParse(core,out na.Core);

            string rpet=reader["REPEAT"].ToString();
            Boolean.TryParse(core,out na.Repeat);
            int tse,cde;

                int.TryParse(reader["TS"].ToString(),out tse) ;
                int.TryParse(reader["CD"].ToString(),out cde);
            na.TS=tse;
            na.CD=cde;
                string contente=reader[7].ToString();
                na.Content = contente;


            string grade=reader["Grade"].ToString();
            na.Grade = grade;

            a[i] = na;


        }

        conn.Close();
        return a;
    }

1)问题是,当我尝试访问 NaiveBayes 的属性时,它会提供 null引用异常

     Forexample :
          a[i].Name="ABC";
         This will raise the following Exception.
    Unhandled Exception: System .NullReferenceException :Object Reference is not set to an instance of object

2)第二个问题是a [i]中的所有对象必须具有不同的值但是值被复制(最后一次迭代)

    Forexample when i=2 ,and a[1].Name was "IstName" .and a[2].Name must be "2ndName". At the end both a[1].Name and a[2].Name has same value"2ndName" 

================================这是 NaiveBayes 类==== ==================

 namespace NaiveBayes1
 {
  public class NaiveBayes 
  {
    public string Name ;
    public string Dept ;
    public string Content ;
    public string Grade ;
    public Boolean Core ;
    public Boolean Repeat;
    public int TS ;
    public int CD ;


    public NaiveBayes()
    {

    Name = "";
    Dept = "";
    Content = "";
    Grade = "";
    Core = false;
    Repeat = false;
    TS = 0;
    CD = 0;    
    }
}

================问题2的回答========================

   NaiveBayes[] na = new NaiveBayes[5];
   NaiveBayes[0].Name ="ABC" // NaiveBayes[0] is null.  The array was allocated but not initialized.
               // There is no NaiveBayes class to set the Name for.

完整答案在这里What is a NullReferenceException, and how do I fix it?

3 个答案:

答案 0 :(得分:3)

您的第一个错误很可能是因为您的数据库中的行数少于10行,因此并未设置所有10个数组元素。

第二个问题是因为您为每个数组元素分配了相同的实例。最简单的解决方法:

NaiveBayes[] a=new NaiveBayes[10];
NaiveBayes1.NaiveBayes na;

int i = 0;
while (reader.Read())
{
    na = new NaiveBayes();
    i++;

针对第一个问题提出的一个解决方案是使用list而不是数组:

List<NaiveBayes> nbs = new List<NaiveBayes>();

int i = 0;
while (reader.Read())
{
    NaiveBayes1.NaiveBayes na = new NaiveBayes();
    i++;

    //...

    nsb.Add(na);
}

然后,当您尝试使用它时,可以针对nbs.Count属性验证所需的索引。或者您可以使用.ToArray()从方法中返回。

答案 1 :(得分:1)

我想这个:

NaiveBayes1.NaiveBayes na = new NaiveBayes();

应该在while循环中,所以你在每个循环中得到一个新的,否则你每次只添加相同的对象。

答案 2 :(得分:1)

您的数据库是一般选择语句,但您预计会有十条记录。如果记录少于10条,您将获得Null Reference Exception,如果超过10条,您将获得Index Out of Range Exception。要解决此问题,请使用List或其他可调整大小的容器。

此外,重复值的第二个问题可能是因为您正在循环中重用NaiveBayes类的实例。

此外,由于相当多的变量充当数据阅读器和对象之间的中介,我已经简化了。

public NaiveBayes[] ReadOBj()
{
    SqlConnection conn = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand(@"SELECT NAME, CODE, DEPARTMENT, TS, CD, REPEAT,        CORE, [Content], Grade 
    FROM Transcript
    WHERE (Grade <> 'UNKNOWN')", conn);

    conn.Open();
    SqlDataReader reader = command.ExecuteReader();
    List<NaiveBayes> a = new List<NaiveBayes>();

    while (reader.Read())
    {
        NaiveBayes1.NaiveBayes na = new NaiveBayes();
        na.Name = (string)reader["NAME"];
        na.Dept = reader["DEPARTMENT"].ToString();
        Boolean.TryParse(reader["CORE"].ToString(), out na.Core);
        Boolean.TryParse(reader["REPEAT"].ToString(),out na.Repeat);
        int.TryParse(reader["TS"].ToString(),out na.TS) ;
        int.TryParse(reader["CD"].ToString(),out na.CD);
        na.Content = reader["Content"].ToString();
        na.Grade = reader["Grade"].ToString();

        a.Add(na);
    }

    conn.Close();
    return a.ToArray();
}