ping.send字符串参数不起作用

问题描述 投票:0回答:1

我最近正在研究一个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“

c# string winforms visual-studio-2017 internet-connection
1个回答
0
投票

据我所知,你只是错过了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为前缀。

现在去看看the static keyword in C#

或者,您可以更改方法以接受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");
© www.soinside.com 2019 - 2024. All rights reserved.