无法在C#中将类型void隐式转换为对象错误
我在允许我使用自己的代码扩展其功能的应用程序中使用此功能.
I'm using this in an application where I am allowed to extend its functionality using my own code.
它已经用C#编码.
Result()
将返回从我的Node.js服务器( FinalResponse
)获得的答案,我将在下面的应用程序中访问它,但是尝试使用EchoOut()时,标题出现错误.
Result()
will return the answer it gets from my Node.js server (FinalResponse
) and I'm going to access it in the application like below, but I get the error in the title when I try to use EchoOut().
var returnedValue = Lib.Result();
App.EchoOut(returnedValue); // EchoOut allows you to test the function you wrote, it echoes string on the screen, but in this case, it gives an error.
错误
cannot implicitly convert type void to object
当我单独测试 Lib.Result()
时,我看到应用正在发出请求,但是我无法将返回值分配给变量.
When I test the Lib.Result()
alone, I see the request is being made by the app, but I can't assign the returned value to a variable.
如何将 FinalResponse的
值分配给 returnedValue
变量?
我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace MainNameSpace
{
public class Lib
{
public void Result()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("192.168.1.101:8000/mytest");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string FinalResponse = stream.ReadToEnd();
Console.WriteLine(FinalResponse);
}
}
}
您需要将 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.