我最近正在研究一个C#Winform项目中的一个函数,它检查IP连接状态(因为我已经测试过,它工作正常),这是我的代码。
public static bool checkConnection()
{
Ping pinger = new Ping();
try
{
return pinger.Send("192.168.0.2").Status == IPStatus.Success;
}
catch
{
Console.WriteLine("connection fail");
return false;
}
}
但是当我试图取代pinger.Send("192.168.0.2").Status == IPStatus.Success;
时
使用以下代码
String router_IP = "192.168.0.2";
return pinger.Send(router_IP).Status == IPStatus.Success;
编译器就是不接受这种用法.....
然后,我尝试了以下代码,它也不会工作。
IPAddress ip_address = IPAddress.Parse(router_IP);
return pinger.Send(ip_address).Status == IPStatus.Success;
所以,我的问题是:有没有人知道如何在pinger.Send
中解析字符串变量而不是只发送“192.168.0.2”?
这是我的Visual Studio 2017的图像(抱歉有中文谚语,我将翻译VS 2017提供的建议)
The error message I got from VS 2017错误消息说:“它需要查找引用的对象,因此它可以使用非静态方法或属性”FileUpload.router_IP“
据我所知,你只是错过了static
关键字。
您的代码看起来像这样:
string router_IP = "192.168.0.2";
public static bool checkConnection()
{
Ping pinger = new Ping();
try
{
return pinger.Send(router_IP).Status == IPStatus.Success;
}
catch
{
Console.WriteLine("connection fail");
return false;
}
}
将第一行更改为:
static string router_IP = "192.168.0.2";
请注意,它现在以static
为前缀。
或者,您可以更改方法以接受IP地址的string
表示作为参数:
public static bool checkConnection(string router_IP)
{
Ping pinger = new Ping();
try
{
return pinger.Send(router_IP).Status == IPStatus.Success;
}
catch
{
Console.WriteLine("connection fail");
return false;
}
}
现在你只需这样称呼它:
var result = checkConnection("192.168.0.2");