gpt4 book ai didi

c# - 无法从字符转换为字符串

转载 作者:太空狗 更新时间:2023-10-30 00:53:47 26 4
gpt4 key购买 nike

我希望弹出一个消息框,显示通过文本框从用户那里接受的字符串的第一个字符,当用户单击消息框的确定按钮时,下一个字符会在消息框中弹出,直到达到 null。

我已经创建了这个程序,但由于明显的原因,它给出了以下错误:“无法从‘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.Windows.Forms;

namespace loop_Message
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void submit_Click(object sender, EventArgs e)
{
string str;
str = stringTxt.Text;
for (int i = 0; str[i] != null; i++)
{
MessageBox.Show(str[i]);
}
}
}
}

最佳答案

使用这个:

foreach (char c in stringTxt.Text)
{
MessageBox.Show(c.ToString());
}

MessageBox.Show()需要一个 string 参数,因此您需要将字符转换为字符串。

你的循环:

for (int i = 0; str[i] != null; i++)

引发 IndexOutOfRangeException.NET 中的字符串不是 C 中的字符数组。它们实际上以 null 结尾,但您无法使用其索引(等于 Length)访问 null 字符。 CLR 检查索引,因为它超出了字符串的有效索引范围(0Length-1),抛出异常。

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

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