c# - 为什么我的 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;
}
}
解决方案
推荐阅读
- javascript - 使用 require() 加载功能组件
- python - 当我使用 Python 将列表转换为 CSV 文件时,为什么我的数据之间有空白行?
- java - 为什么即使在测试失败后 Maven 也会运行测试?
- tradingview-api - 如何绘制 2 行 plotchar 或其他方法,这样每行之间就有一个空格?
- python - ModuleNotFoundError:Jupyter 笔记本上没有名为“cv2”的模块
- asp.net - 如何在 ASP.NET Web 表单应用程序中添加 Telerik Web 报表设计器控件?
- javascript - react-select:禁用默认样式
- python - 添加到 Dataframe 的新列不断消失
- python - 如何将 pandas 过滤器应用到 for 循环中
- java - 将自然语言句子转换为机器可读格式的最佳方法?