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

逐个发送文本字符报错:无法将char转换为string,求解决方案

问题原因

报错的核心是类型不匹配:unitStr[i]获取的是单个char(字符)类型的值,但SendText方法要求传入的参数是string(字符串)类型,编译器因此提示无法转换。

解决方法

只需把单个字符转换成字符串类型再传入即可,以下是几种可行写法:

方法1:用ToString()转换

直接对char调用ToString()方法,将其转为字符串:

public void SelectUnit(string unitStr)
{
    // Enter the text for the search
    new LufasWebManager().Stall(500);
    for (int i = 0; i < unitStr.Length; i++)
    {
        unitTxt.SendText(unitStr[i].ToString()); // 转换为字符串
        Thread.Sleep(10);
    }
    
    new LufasWebManager().Stall(2000);

    // Locate the correct result
    var unitSearchResult = driver.FindElement(By.XPath($"//lfs-search-results-drop-list/div/div/div[contains(text(), '{unitStr}')]"));

    // And then click it
    unitSearchResult.Click();
}

方法2:用Substring()截取单个字符

通过字符串的Substring方法,从索引i处截取长度为1的子字符串:

unitTxt.SendText(unitStr.Substring(i, 1));

方法3:用字符数组构造字符串

将单个字符放到数组中,再通过字符串构造方法生成字符串:

unitTxt.SendText(new string(new[] { unitStr[i] }));

以上三种方法都能解决类型不匹配的问题,任选其一即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:07:44