简体   繁体   English

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

[英]Unhandled Exception: NullReferenceException:Object Reference not set to the

I know i am making a silly mistake but unfortunately i am unable to find it even after a lot of Debug. 我知道我犯了一个愚蠢的错误,但是不幸的是,即使经过大量调试,我也找不到它。 I have made a class "naivebayes" and other class Connect 上了一堂“ naivebayes” ,其他上课了Connect

======================== This is a method of Connect ================== ========================这是一种连接方法===================

  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) The problem is when i try to access attributes of NaiveBayes it gives null reference exception . 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)The 2nd problem is that all object in a[i] must have distinct values but the value is replicated(of last iteration) 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" 

================================This is NaiveBayes class====================== ==============================这是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;    
    }
}

================Answer of Problem 2======================== ===============问题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.

Full Answer is here What is a NullReferenceException, and how do I fix it? 完整答案在这里。 什么是NullReferenceException,我该如何解决?

Your first error comes most probably from the fact, that there are less than 10 rows in your DB, so not all of 10 array elements are being set. 您的第一个错误很可能来自以下事实:数据库中的行少于10个,因此并非所有10个数组元素都已设置。

The second problem is because you assign the same instance to each array element. 第二个问题是因为您为每个数组元素分配了相同的实例。 Simplest fix: 最简单的解决方法:

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

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

One proposed solution for the first problem is to use list instead of an array: 对于第一个问题,一个建议的解决方案是使用列表而不是数组:

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

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

    //...

    nsb.Add(na);
}

So then when you attempt to use it, you can verify the desired index against nbs.Count property. 因此,当您尝试使用它时,可以针对nbs.Count属性验证所需的索引。 Or you can return it from your method using .ToArray() . 或者,您可以使用.ToArray()从您的方法返回它。

I think this: 我认为这:

NaiveBayes1.NaiveBayes na = new NaiveBayes();

should be in the while loop so you get a new one on each loop, otherwise your just adding the same object each time. 应该在while循环中,这样您就可以在每个循环中获得一个新对象,否则每次只需添加相同的对象即可。

Your database is a general select statement but you are expecting exactly ten records back. 您的数据库是常规的select语句,但是您期望返回恰好有10条记录。 If there are less than 10 records, you will get the Null Reference Exception , if there are more than 10, you will get an Index Out of Range Exception . 如果少于10条记录,则将获得Null Reference Exception ;如果有10条以上,则将获得Index Out of Range Exception To work around this, use a List or another resizeable container. 要解决此问题,请使用List或其他可调整大小的容器。

Also, the second issue of repeated values is possibly because you are reusing the instances of NaiveBayes class within the loop. 另外,重复值的第二个问题可能是因为您正在循环中重用NaiveBayes类的实例。

Also, as quite a few variables are acting as intermediaries between the data reader and object, I have simplified. 另外,由于相当多的变量充当数据读取器和对象之间的中介,因此我进行了简化。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未处理NullReferenceException,未将对象引用设置为对象的实例 - NullReferenceException was unhandled, Object Reference not set to an instance of an object 处理请求时发生未处理的异常。 NullReferenceException:Object 引用未设置为 object 的实例 - An unhandled exception occurred while processing the request. NullReferenceException: Object reference not set to an instance of an object 未处理的异常。 System.NullReferenceException:未将对象引用设置为对象的实例 - Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object C#未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例 - C# Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object CSharp未处理的异常:System.NullReferenceException:对象引用未设置为对象的实例 - CSharp Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object 未处理C#NullReferenceException-未将对象引用设置为对象的实例 - C# NullReferenceException was unhandled - Object reference not set to an instance of an object 类型&#39;System.NullReferenceException&#39;的异常:对象引用未设置为对象的实例 - An exception of type 'System.NullReferenceException' : Object reference not set to an instance of an object C#未处理的异常:对象引用未设置为对象的实例 - c# unhandled exception: object reference not set to an instance of an object NullReferenceException:对象引用未设置为对象#2的实例 - NullReferenceException: Object reference not set to an instance of an object #2 错误:NullReferenceException:未将对象引用设置为对象的实例 - ERROR: NullReferenceException: Object reference not set to an instance of an object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM