在C#应用程序中获取NullReferenceException并且无法查看解除引用为空的原因

Dan*_*mta -1 c# nullreferenceexception windows-applications

我编写了简单的代码,由于获得NullReferenceException的原因我不知道,由于某些特殊原因无法正常工作.

这是简单的应用程序

namespace App1
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {

        private string[] IPToCheck;
        private List<string> IPRange;
        private bool CorrectNetwork = false;

        public MainPage()
        {
            this.InitializeComponent();
            var hostnames = NetworkInformation.GetHostNames();
            foreach (var hn in hostnames)
            {
                if (hn.IPInformation != null &&
                   (hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
                   || hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
                {
                    IPToCheck = hn.DisplayName.Split(new char[] { '.' });
                    if (IPToCheck.Count() == 4)
                    {
                        Debug.WriteLine("Correct");
                        CorrectNetwork = true;
                    }
                    if (CorrectNetwork)
                    {
                        Debug.WriteLine("{0}.{1}.{2}.",IPToCheck);
                        GenerateIPs(IPToCheck);
                        break;                        
                    }
                }
            }
        }

        private void GenerateIPs(string[] IPToCheck)
        {
            for (int i = 0; i < 255; i++)
            {
                Debug.WriteLine(IPToCheck[0] + "." + IPToCheck[1] + "." + IPToCheck[2] + "." + i.ToString());
                IPRange.Add(IPToCheck[0] + "." + IPToCheck[1] + "." + IPToCheck[2] + "." + i.ToString());
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

运行此时,我得到以下输出:

Correct
192.168.10.
192.168.10.0
A first chance exception of type 'System.NullReferenceException' occurred in App1.Windows.exe
Run Code Online (Sandbox Code Playgroud)

它强调:

IPRange.Add(IPToCheck[0] + "." + IPToCheck[1] + "." + IPToCheck[2] + "." + i.ToString());
Run Code Online (Sandbox Code Playgroud)

似乎第一个"ip"是在GenerateIPs方法的for循环中生成的.

为什么会发生这种NullReferenceException?谢谢!

Jur*_*eri 6

你忘了添加:

this.IPRange = new List<string>();
Run Code Online (Sandbox Code Playgroud)

在你的MainPage构造函数中.