-3

好的,所以我在我的 c# 脚本中添加了一个函数来获取 ip 地址并将输出作为字符串发送到变量中,这是我的来源

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Net;
using System.IO;


namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        string URL = "http://localhost/test2.php";
        WebClient webClient = new WebClient();

        NameValueCollection formData = new NameValueCollection();
        formData["var1"] = formData["var1"] = string.Format("MachineName: {0}", System.Environment.MachineName);
        formData["var2"] = stringGetPublicIpAddress();
        formData["var3"] = "DGPASS";

        byte[] responseBytes = webClient.UploadValues(URL, "POST", formData);
        string responsefromserver = Encoding.UTF8.GetString(responseBytes);
        Console.WriteLine(responsefromserver);
        webClient.Dispose();
        System.Threading.Thread.Sleep(5000);
    }

    private static string stringGetPublicIpAddress()
    {
        throw new NotImplementedException();
    }
        private string GetPublicIpAddress()
    {
        var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");

        request.UserAgent = "curl"; // this simulate curl linux command

        string publicIPAddress;

        request.Method = "GET";
        using (WebResponse response = request.GetResponse())
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                publicIPAddress = reader.ReadToEnd();
            }
        }

        return publicIPAddress.Replace("\n", "");

    }
    }
    }

基本上我已经创建了这个功能

private static string stringGetPublicIpAddress()

我将它作为变量发送

formdata["var2"] = stringGetPublicIpAddress();

我收到此错误

throw new NotImplementedException();  === NotImplementedException was unhandled
4

1 回答 1

0

你……没有实现这个方法。你有这个:

private static string stringGetPublicIpAddress()
{
    throw new NotImplementedException();
}

所以当然,任何时候你调用那个方法,它都会抛出那个异常。不过,看起来您确实在此处实现了所需的方法:

private string GetPublicIpAddress()
{
    // the rest of your code
}

也许这是某些复制/粘贴错误的结果?尝试摆脱引发异常的小方法并将实现的方法更改为静态:

private static string GetPublicIpAddress()
{
    // the rest of your code
}

然后在您调用它的任何地方更新:

stringGetPublicIpAddress();

对此:

GetPublicIpAddress();

这真的只是看起来像复制/粘贴错误以奇怪的方式出错。或者您可能正在为静态方法和实例方法之间的区别而苦苦挣扎?也许您实现了该方法,但编译器建议您需要一个静态方法?有很多关于静态与实例方法/成员的内容需要阅读,我不会在这里真正深入。这是面向对象编程中的一个重要概念。

在这种特殊情况下,由于您处于静态方法 in 的上下文中,因此您在该类(类)上Main调用的任何内容也必须是静态的,除非您创建这样的实例MainProgramProgram

var program = new Program();

这将允许您调用实例方法Program

program.SomeNonStaticMethod();

但是对于像这样的小型应用程序,这并不是必需的。

于 2013-10-06T21:39:13.953 回答