Public类成员的NullReferenceException

本文关键字:NullReferenceException 成员 Public | 更新日期: 2023-09-27 18:29:08

当调用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(声明为public)会返回为null。这两个方法都是从同一类中的一个单独方法中调用的。

宣言是一流的:

class FlightPlan
{
   //Init Pg.1 data
    public WYPT Dep, Dest, Altn;

要设置的调用来自不同的类:

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

Public类成员的NullReferenceException

代码中唯一可以在GetDepAirport中返回NullReferenceException的部分是Dep.IdentDepIdent可以为null。如果您为这两个都添加了null检查,那么该方法将运行良好。

至于为什么这两个都为空,可能是因为:

  • 您在呼叫GetDepAirport之前未呼叫SetDepAirport
  • FetchDBAirport要么返回null,要么返回Ident为null的Dep实例
  • 调用GetDepAirport的代码正在其他地方更改Dep的值
  • Dep没有正确存储值,因此可能是属性定义中的问题