C# 错误消息:无法将类型“字符串”转换为“字符串[]”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2337928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:32:55  来源:igfitidea点击:

Error message: Cannot convert type 'string' to 'string[]'

c#asp.net-3.5

提问by user279521

I am creating a dynamic array, and getting an error:

我正在创建一个动态数组,并收到一个错误:

Error message: Cannot convert type 'string' to 'string[]'

错误消息:无法将类型“字符串”转换为“字符串[]”

The code is:

代码是:

arrTeamMembers += tb.Text;

tb.Text contains values such as "Michael | Steve | Thomas | Jeff | Susan | Helen |"

tb.Text 包含诸如“Michael | Steve | Thomas | Jeff | Susan | Helen |”之类的值

I am trying to pass the values from tb.Text to arrTeamMembers. I am NOT trying to split the text. How can I resolve this error?

我试图将值从 tb.Text 传递给 arrTeamMembers。我不是要拆分文本。我该如何解决这个错误?

采纳答案by Foole

You can't just add strings to an array of strings.

您不能只将字符串添加到字符串数组中。

Depending on what you are actually trying to do, you might want this:

根据您实际尝试执行的操作,您可能需要:

string[] arrTeamMembers = new string[] { tb.Text };

or

或者

arrTeamMembers[0] = tb.Text;

You probably want to use a List instead.

您可能想改用 List。

List<string> stringlist = new List<string>();
stringlist.Add(tb.Text);

回答by David Morton

The problem is, arrTeamMembers is an array of strings, while tb.Text is simply a string. You need to assign tb.Text to an index in the array. To do this, use the indexerproperty, which looks like a number in square brackets immediately following the name of the array variable. The number in the brackets is the 0-based index in the array where you want to set the value.

问题是, arrTeamMembers 是一个字符串数组,而 tb.Text 只是一个字符串。您需要将 tb.Text 分配给数组中的索引。为此,请使用indexer属性,它看起来像紧跟在数组变量名称后面的方括号中的数字。括号中的数字是数组中要设置值的从 0 开始的索引。

arrTeamMembers[0] += tb.Text;

回答by Andrew Hare

Try this:

尝试这个:

arrTeamMembers = tb.Text.Split('|');

回答by JDMX

If you are trying to split the text in the textbox then

如果您尝试拆分文本框中的文本,则

arrTeamMembers = tb.Text.Split( '|' );

If this does not work, are you trying to append the textbox to the end of the array?

如果这不起作用,您是否尝试将文本框附加到数组的末尾?

if ( arrTeamMembers == null )
  arrTeamMembers  = new string[0];

string[] temp = new string[arrTeamMembers.Length + 1];
Array.Copy( temp , 0, arrTeamMembers, 0, arrTeamMembers.Length );
temp[temp.Length - 1] = tb.Text;
arrTeamMembers = temp;