字符串到字符串,仍然收到错误"cannot convert from 'string' to 'int'"



我需要帮助来理解为什么我的程序会抛出这个错误:

无法从"字符串"转换为"int">

当列表和tVal都是字符串时。

我在

List<string> testitems = new List<string>(tVal);

请指教。

abc是一个带有一些随机数的 int 数组。

static void Main()
{
string tVal = "";
List<int> result = new List<int>();
for (int i = 0; i < abc.Length; i++)
{
if (abc[i] == 7)
{
result.Add(0);
i++;
}
else
{
result.Add(abc[i]);
}
foreach (var item in result)
{
tVal += item.ToString();
}                            
}
List<string> testitems = new List<string>(tVal);
//more code
}

要将对象添加到列表中,您可以使用:

List<string> testitems = new List<string>() { tVal };  //(like @GSerg suggested in the comments)

或:

List<string> testitems = new List<string>();
testitems.Add(tVal);

tVal放入大括号中,如下所示:

List<string> testitems = new List<string>() { tVal };

列表的官方文档:https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netcore-3.1

new List<string>(tVal)

您提交了 tVal 作为第一个构造函数参数。编译器可以找到的最接近的匹配项是List<T>(Int32)。Wich 有一个无效的字符串 -> Int 转换。

这不是初始化集合的方法!您可以:

  • 使用几乎可以将任何泛型集合作为输入的构造函数 (List<T>(IEnumerable<T>)(
  • 创建列表后手动添加单个元素(Charbels 解决方案(
  • 使用集合初始值设定项语法(如 Marci 所示(

相关内容

最新更新