You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#新手求助:WebService报错“无法将void隐式转换为string”

解决“Cannot implicitly convert type 'void' to 'string'”错误

嘿,作为C#新手遇到这个问题太正常了,我帮你把问题拆解清楚:

错误核心原因

你代码里调用的con.setItemDims()是一个**无返回值(void类型)**的WebService方法——它只负责执行发送数据的操作,不会返回任何字符串结果,但你却试图把它的调用结果赋值给string result变量,这就好比硬要把一个空盒子里的东西倒进另一个盒子,自然会触发类型转换错误。

另外看你的代码,这个方法其实已经通过ref res这个参数来传递返回结果了,所以你根本不需要去接收它的返回值,调用方法后直接用res变量就能拿到返回内容。

修正后的代码

我帮你调整了代码,还顺便修正了一个拼写小错误(tb_lenght应该是tb_length,少了个字母h,虽然不是当前错误的原因,但之后可能会引发其他问题):

public partial class Window : System.Windows.Forms.Form 
{ 
    WebServ.ItemDimWs con = new WebServ.ItemDimWs(); 
    decimal length, width, height, weight, rescode; 
    string user, article, res; 

    public Window() 
    { 
        InitializeComponent(); 
    } 

    private void Window_Load(object sender, EventArgs e) { } 

    public void btn_send_Click(object sender, EventArgs e) 
    { 
        // 修正拼写错误:tb_lenght -> tb_length
        length = Convert.ToDecimal(tb_length.Text.ToString()); 
        width = Convert.ToDecimal(tb_width.Text.ToString()); 
        height = Convert.ToDecimal(tb_height.Text.ToString()); 
        weight = Convert.ToDecimal(tb_weight.Text.ToString()); 
        article = tb_article.Text; 
        user = tb_user.Text; 

        // 直接调用方法,无需赋值给string变量(因为方法返回void)
        con.setItemDims(article, length, width, height, weight, weight, "EA", "KG", "CM", user, ref rescode, ref res); 

        // 用ref参数res来展示返回结果
        MessageBox.Show(res); 
        MessageBox.Show("Resp:" + rescode + res + "!!!"); 
    } 
}

额外小提示

以后遇到类似WebService方法的问题,你可以在Visual Studio里把鼠标悬停在方法名(比如setItemDims)上,查看智能提示的方法签名说明,或者查看WebService的官方文档,这样能快速搞清楚哪些参数是输入值,哪些是通过ref/out传递的输出结果。

内容的提问来源于stack exchange,提问作者emnt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:18:56