gpt4 book ai didi

c# - Foreach 循环无法将字符转换为字符串

转载 作者:可可西里 更新时间:2023-11-01 09:42:07 24 4
gpt4 key购买 nike

无论出于何种原因,这个看似简单的方法都行不通。具体来说,Foreach 循环给我这个错误“错误 1 ​​无法将类型‘char’转换为‘string’”。我做了一些研究,虽然它不想暴露自己。希望你们知道,非常感谢您的帮助。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace A_HtmlEditor
{
public partial class Form1 : Form
{
AutoCompleteStringCollection data = new AutoCompleteStringCollection();

public Form1()
{
InitializeComponent();
}

// The error occurs in the foreach loop below
private void textBox1_TextChanged(object sender, EventArgs e)
{
webBrowser1.DocumentText = textBox1.Text;

foreach(string s in textBox1.Text)
{
data.Add(s);
}
}
}
}

顺便说一句我想知道我在这里的时候,你们中有人碰巧知道是否有可能查明是否有按钮点击,例如关机按钮?或者,如果这不可能,是否有一种方法可以知道计算机何时即将关闭。

我再次感谢这一切,谢谢。

最佳答案

textBox1.Text 是一个字符串(不是字符串的集合)。所以当你这样做时:

foreach (string s in textBox1.Text)
{
data.Add(s);
}

它试图将字符串视为一个集合。这确实有效,因为 string 实际上是 char 的数组。问题是您在声明 string s 时试图将每个 char 转换为 string

如果你真的想将每个字符添加到data,那么你可以将每个char转换成一个string:

// This takes each character from textBox1.Text,
// converts it to a string, and adds it to data
foreach (char chr in textBox1.Text)
{
data.Add(chr.ToString());
}

或者,如果您的 textBox1 是一个多行文本框,并且您试图将每一行添加到 data,您可以在 上拆分文本NewLine 字符获取字符串列表,并像这样添加它们:

// This takes each line from a multi-line text box and adds it to data
foreach (string line in textBox1.Text.Split(new[] { '\n' }))
{
data.Add(line);
}

关于c# - Foreach 循环无法将字符转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27370276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com