当调用 GetDepAirport() 方法时,以下代码将引发“在...中发生类型为 'System.NullReferenceException' 的未处理异常”。
public WYPT GetDepAirport()
{
Console.WriteLine("Retrieving Airport in GetDepApt()");
Console.WriteLine("Departure Airport is {0}", Dep.Ident);
return Dep;
}
public void SetDepAirport(String ident)
{
Console.WriteLine("Setting Airport with ident {0}, ident");
Dep = FetchDBAirport(ident);
Console.WriteLine("WYPT Dep is set to {0}", Dep.Ident);
}
输出是:
Setting Airport with ident KABQ
WYPT Dep is set to KABQ
Retrieving Airport in GetDepApt()
紧随其后的是一连串的例外。当从 GetDepAirport() 方法调用时,我无法弄清楚为什么Dep(声明为公共)返回为null 。这两种方法都是从同一类中的单独方法中调用的。
声明位于类的顶部:
class FlightPlan
{
//Init Pg.1 data
public WYPT Dep, Dest, Altn;
对 set 的调用来自不同的类:
FlightPlan FPlan = new FlightPlan();
FPlan.SetDepAirport(Dep);
稍后会调用 Get:
public void GetFPlan()
{
for (int i = 0; i < 14; i++)
{
Waypoint[i] = new WYPT();
}
Waypoint[0] = GetDepAirport();
Waypoint[1] = DISCON;
同一 FlightPlan 类中的 FetchDBAirport 方法
private WYPT FetchDBAirport(String airport)
{
WYPT Airport = new WYPT();
String databasepath = "C:\\Users\\Family\\documents\\visual studio 2012\\Projects\\FMST\\FMST\\Database\\NavData.mdf";
SqlConnection myConnection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=" + databasepath + ";Integrated Security=True");
try
{
myConnection.Open();
SqlCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM Airports WHERE Ident='" + airport + "';";
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Airport.Ident = (String)rdr.GetValue(0);
Airport.Lat = (decimal)rdr.GetValue(2);
Airport.Lon = (decimal)rdr.GetValue(3);
Airport.Elev = (decimal)rdr.GetValue(4);
myConnection.Close();
return Airport;
}
catch (Exception e)
{
Console.WriteLine(e.ToString() + "Happy Face");
String ErrorMsg = "NOT FOUND";
Airport.Ident = ErrorMsg;
return Airport;
}