且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在C#中将类型void隐式转换为对象错误

更新时间:2022-02-23 14:40:20

您需要将 Result 方法的返回类型更改为 string 并返回FinalResponse 而不是将其写入控制台.

You need to change the return type of the Result method to string and return the FinalResponse instead of writing it to the console.

public string Result() // <-- "string" instead of "void"
{
    var request = (HttpWebRequest)WebRequest.Create("192.168.1.101:8000/mytest");

    using (var response = (HttpWebResponse)request.GetResponse())
    using (var stream = response.GetResponseStream())
    using (var reader = new StreamReader(stream))
    {
        return reader.ReadToEnd(); // <-- return the result
    }
}

使用一次性对象包装代码(在这种情况下,是 HttpWebResponse Stream StreamReader 类型的对象)也被认为是一种好习惯)和 using 块.

It is also considered good practice to wrap the code using disposable objects (in this case, objects of type HttpWebResponse, Stream and StreamReader) with using blocks.

我还***使用了 var 而不是显式地写出变量的类型,因为在声明的右侧,这些类型已经很明显了.

I also took the liberty of using var instead of explicitly writing out the types of the variables because the types are already obvious from the right hand sides of the declarations.