公共类成员的NullReferenceException

时间:2013-08-26 03:48:42

标签: c#

以下代码抛出"未处理的类型' System.NullReferenceException'发生在..."当调用GetDepAirport()方法时。

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

其次是一系列例外情况。我无法弄清楚为什么 Dep (声明为public)在从GetDepAirport()方法调用时返回 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;
        }

1 个答案:

答案 0 :(得分:1)

可以在GetDepAirport中返回NullReferenceException的代码的唯一部分是Dep.IdentDepIdent可以为null。如果为这两个添加空检查,则该方法将正常运行。

至于为什么其中任何一个为空,可能是因为:

  • 在致电SetDepAirport
  • 之前,您尚未致电GetDepAirport
  • FetchDBAirport要么返回null,要么返回DepIdent为空的实例。
  • 调用GetDepAirport的代码正在改变其他地方的Dep的值
  • Dep未正确存储值 - 因此属性定义中可能存在问题