我知道我犯了一個愚蠢的錯誤,但不幸的是,即使經過大量的調試後,我仍然無法找到它。 我已經作出了類「naivebayes」和其他類連接未處理的異常:NullReferenceException:對象引用未設置爲
========================這是的方法連接 ==================
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屬性它給空引用異常 。
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)第二個問題是,在[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?
可能重複[什麼是一個NullReferenceException,如何解決呢?(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i - 固定它) – Alberto