繁体   English   中英

在C#应用程序中获取NullReferenceException并看不到取消引用为null的原因

[英]Getting NullReferenceException in a C# App and cant see reason why dereference is null

我已经编写了简单的代码,由于某些我不知道的原因而导致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());
            }
        }
    }
}

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

Correct
192.168.10.
192.168.10.0
A first chance exception of type 'System.NullReferenceException' occurred in App1.Windows.exe

它强调:

IPRange.Add(IPToCheck[0] + "." + IPToCheck[1] + "." + IPToCheck[2] + "." + i.ToString());

似乎在GenerateIPs方法的for循环中生成了第一个“ ip”。

为什么会发生此NullReferenceException? 谢谢!

您忘记添加:

this.IPRange = new List<string>();

在您的MainPage构造函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM