无法在C#中将类型void隐式转换为对象错误 [英] cannot implicitly convert type void to object error in C#

查看:82
本文介绍了无法在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.

这篇关于无法在C#中将类型void隐式转换为对象错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆