“尝试访问类嵌套列表时,对象引用未设置为对象的实例”

时间:2018-03-06 23:41:03

标签: c# asynchronous uwp nullreferenceexception nested-lists

我正在编写一个C#UWP程序来跟踪天气数据。当试图访问WeatherPage类中的行Debug.WriteLine("DEBUG IN WEATHERPAGE: " + myForecast.mysortedDays[1][1].desc);时,我得到“对象引用未设置为对象的实例”。 sortedDays是一个嵌套列表,我需要能够完全访问。我知道在我的GetWeather方法中sortedDays正在填充,但在从另一个类引用时为null。我觉得这是一个调用setter方法的情况,但不是我无法用链表成功完成这个

namespace WeatherForecast
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WeatherPage : Page
{
    Forecast myForecast;
    public WeatherPage()
    {
        this.InitializeComponent();

         myForecast = new Forecast();
        // Task task =myForecast.GetWeather("id=2964179");

        myForecast.GetWeather("id=2964179");

        Debug.WriteLine("DEBUG IN WEATHERPAGE: " + myForecast.sortedDays[1][1].desc);
    }
}
}


namespace WeatherForecast
{
class Forecast
{
    public List<List<WeatherController>> sortedDays { get; set; }
    public RootObject result { get; set; }

    public Forecast()
    {

    }
 public async void GetWeather(string cCode)
    {
        // DEBUG
        Debug.WriteLine("DEBUG: Started getWeather");
        string cityCode = cCode;
        string apiKey = "myapikey";
        // string cityCode = "id=2964179";
        string url = "myurl" + cityCode + apiKey;


        var uri = new Uri(url);
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.GetAsync(uri))
            {
                using (IHttpContent content = response.Content)
                {
                    var json = await content.ReadAsStringAsync();

                    result = JsonConvert.DeserializeObject<RootObject>(json);
                    //  SortWeather();

                    // create a list of weatherController lists to hold each day
                    // made public for global access
                    List<List<WeatherController>> sortedDays = new List<List<WeatherController>>();
                    //    sortedDays = new List<List<WeatherController>>();

                    //create a list of weatherController objects to hold each hourly interval
                    List<WeatherController> sortedHours = new List<WeatherController>();

                    // a base time
                    DateTime prevDate = Convert.ToDateTime("2000-01-01");
                    int counter = 0;

                    // iterate through result list  
                    for (int i = 0; i < result.list.Count(); i++)
                    {
                        // if the date is greater than the previous date add the sortedHours to sortedDays
                        if (Convert.ToDateTime(result.list[counter].dt_txt).Date > prevDate.Date && counter != 0)
                        {
                            sortedDays.Add(sortedHours);
                            sortedHours = new List<WeatherController>();
                        }
                        WeatherController wController = new WeatherController
                        {
                            dtime = result.list[counter].dt_txt,
                            dayOfWeek = (Convert.ToDateTime(result.list[counter].dt_txt).DayOfWeek).ToString(),
                            temp = result.list[counter].main.temp,
                            humidity = result.list[counter].main.humidity,
                            desc = result.list[counter].weather[0].description,
                            windSpeed = result.list[counter].wind.speed
                        };
                        sortedHours.Add(wController);

                        prevDate = Convert.ToDateTime(result.list[counter].dt_txt);
                        counter++;

                    }
                    // add any left over sortedHours to sortedDays
                    if (sortedHours != null)
                    {
                        sortedDays.Add(sortedHours);
                    }

                    Debug.WriteLine("DEBUG: Finished getWeather");

                }
            }
        }
    }


}
}

1 个答案:

答案 0 :(得分:1)

您正在分配具有相同名称的本地变量。 见A点 所以基本上你从来没有为预测的assigne sortedDays属性。您必须执行 Point B 中的代码 或添加以下行:

this.sortedDays = sortedDays;

namespace WeatherForecast
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class WeatherPage : Page
    {
        Forecast myForecast;
        public WeatherPage()
        {
            this.InitializeComponent();

            myForecast = new Forecast();
            // Task task =myForecast.GetWeather("id=2964179");
            // POINT C
            myForecast.GetWeather("id=2964179").GetAwaiter().GetResult();
            //POINT D
            Debug.WriteLine("DEBUG IN WEATHERPAGE: " + myForecast.sortedDays[1][1].desc);
        }
    }
}

namespace WeatherForecast
{
    class Forecast
    {
        public List<List<WeatherController>> sortedDays { get; set; }
        public RootObject result { get; set; }

        public Forecast()
        {

        }

        public async Task GetWeather(string cCode)
        {
            // DEBUG
            Debug.WriteLine("DEBUG: Started getWeather");
            string cityCode = cCode;
            string apiKey = "myapikey";
            // string cityCode = "id=2964179";
            string url = "myurl" + cityCode + apiKey;


            var uri = new Uri(url);
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(uri))
                {
                    using (IHttpContent content = response.Content)
                    {
                        var json = await content.ReadAsStringAsync();

                        result = JsonConvert.DeserializeObject<RootObject>(json);
                        //  SortWeather();

                        // create a list of weatherController lists to hold each day
                        // made public for global access
                        // POINT A
                        List<List<WeatherController>> sortedDays = new List<List<WeatherController>>(); 

                        // POINT B
                        //    sortedDays = new List<List<WeatherController>>();

                        //create a list of weatherController objects to hold each hourly interval
                        List<WeatherController> sortedHours = new List<WeatherController>();

                        // a base time
                        DateTime prevDate = Convert.ToDateTime("2000-01-01");
                        int counter = 0;

                        // iterate through result list  
                        for (int i = 0; i < result.list.Count(); i++)
                        {
                            // if the date is greater than the previous date add the sortedHours to sortedDays
                            if (Convert.ToDateTime(result.list[counter].dt_txt).Date > prevDate.Date && counter != 0)
                            {
                                sortedDays.Add(sortedHours);
                                sortedHours = new List<WeatherController>();
                            }
                            WeatherController wController = new WeatherController
                            {
                                dtime = result.list[counter].dt_txt,
                                dayOfWeek = (Convert.ToDateTime(result.list[counter].dt_txt).DayOfWeek).ToString(),
                                temp = result.list[counter].main.temp,
                                humidity = result.list[counter].main.humidity,
                                desc = result.list[counter].weather[0].description,
                                windSpeed = result.list[counter].wind.speed
                            };
                            sortedHours.Add(wController);

                            prevDate = Convert.ToDateTime(result.list[counter].dt_txt);
                            counter++;

                        }
                        // add any left over sortedHours to sortedDays
                        if (sortedHours != null)
                        {
                            sortedDays.Add(sortedHours);
                        }

                        Debug.WriteLine("DEBUG: Finished getWeather");

                    }
                }
            }
        }
    }
}

<强> 编辑:
此外,您正在使用async void方法,因此您无需等待任务,因此您将在GetWeather方法结束之前到达 POINT D 中的行。 您可以更改GetWeather方法以返回任务,然后使用 POINT C 同步调用它。虽然我会在LoadingLoaded等事件中执行此操作并使用该语句 await myForecast.GetWeather("id=2964179");

谢谢,