首页 > 解决方案 > 为什么我的 C# 代码在 Windows 上运行但在 Linux 中抛出异常

问题描述

我在 Visual Studio 2019 的 .netcore3.1 中工作,我在代码中编写了一个名为 ping() 的方法。当我在调试模式下运行应用程序时,它工作得非常好。此外,当我为 Windows 发布并执行它时,它工作正常。但是当我为 linux 发布它并在 linux 机器上运行时,它会在“for 循环”上引发 NullReferenceException。异常消息是:System.NullReferenceException:对象引用未设置为对象的实例。在 \PingIo.cs:line 13 (下面代码的第 13 行,即for (int i = 0; i < PING_PACKET_SIZE; i++)

我不明白为什么它在使用常量变量的 for 循环上给出空引用异常?如果有错误,为什么它只在linux上崩溃而不在windows上崩溃?

请帮忙。

        public static double ping(string ipAddress, Int64 timeoutMs)
        {
            const Int32 PING_PACKET_SIZE = 64;
            const Int32 DEFAULT_TIMEOUT_MS = 200;
            try
            {
                Ping pingSender = new Ping();
                PingOptions options = new PingOptions();
                options.DontFragment = true;

                var pingPkt = new List<byte>();

                for (int i = 0; i < PING_PACKET_SIZE; i++)
                {
                    var val = Convert.ToByte(i + '0');
                    pingPkt.Add(val);
                }

                int timeout = (Int32)(timeoutMs == 0 ? DEFAULT_TIMEOUT_MS : timeoutMs);

                PingReply reply = pingSender.Send(ipAddress, timeout, pingPkt.ToArray(), options);
                if (reply.Status == IPStatus.Success)
                {
                    return reply.RoundtripTime;
                }
                else
                {
                    throw new Exception($"Ping Reply was not received! Reply Status: {reply.Status}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return -1;
            }
        }

标签: c#linuxexception.net-core

解决方案


推荐阅读