【问题标题】:C# Why can't I implicitly convert type 'string' to 'System.Collections.Generic.List<int>'?C# 为什么我不能将类型“string”隐式转换为“System.Collections.Generic.List<int>”?
【发布时间】:2016-03-07 13:51:13
【问题描述】:

我正在尝试找出如何解决标题中所述的错误,该错误出现在此 sn-p 中的粗线:

     while (textIn.Peek() != -1)
        {
            string row = textIn.ReadLine();
            string[] columns = row.Split('|');
            StudentClass studentList = new StudentClass();
            studentList.Name = columns[0];
            **studentList.Scores =  columns[1];**
            students.Add(studentList);
        }

前面的代码行可以很好地加载名称,因为它不是我创建的类中的列表,但是“分数”在列表中。我需要做哪些修改?这些值应该在加载应用程序时显示在文本文件的文本框中。

这是“Scores”所在的班级(我已突出显示):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyNameSpace
{

//set the class to public
 public class StudentClass
{

    public StudentClass()
    {
        this.Scores = new List<int>();


    }

    public StudentClass (string Name, List<int> Scores)
    {
        this.Name = Name;
        this.Scores = Scores;
    }



    public string Name
    { get;
      set;
    }

    //initializes the scores
    **public List<int> Scores
    { get;
      set;
    }**


    public override string ToString()
    {
        string names = this.Name;

        foreach (int myScore in Scores)
        { names += "|" + myScore.ToString();

        }
        return names;
    }


    public int GetScoreTotal()
    {
        int sum = 0;

        foreach (int score in Scores)
        { sum += score;


        }

        return sum;

    }

    public int GetScoreCount()
    { return Scores.Count;

    }

    public void addScore(int Score)
    {
        Scores.Add(Score);


    }



}
}

【问题讨论】:

  • 该程序不知道您希望如何将字符串转换为整数列表。如果它采用某种分隔格式,则需要在将其转换为整数列表之前单独对其进行解析。
  • 您的问题不清楚。请解释为什么您认为您应该能够将string 值隐式转换为List&lt;int&gt; 的实例。请提供一个良好的minimal reproducible example,清楚地表明您正在尝试做什么,并准确解释该代码的预期用途。

标签: c# arrays list syntax syntax-error


【解决方案1】:

您不能只将包含数字序列的字符串分配给List&lt;int&gt; 类型的属性。

您需要将字符串拆分为单独的数字,然后解析这些子字符串以获取它们所代表的整数。

例如

    var text = "1 2 3 4 5 6";
    var numerals = text.Split(' ');
    var numbers = numerals.Select(x => int.Parse(x)).ToList();

即在您的代码中替换:

studentList.Scores =  columns[1];

与:

studentList.Scores = columns[1].Split(' ').Select(int.Parse).ToList();

(或您自己的多行、更具可读性/可调试性的等效项。)

您需要根据列中分数的格式修改传递给Split() 的参数。

如果您还没有using System.Linq;,您还需要在顶部添加它。

【讨论】:

  • 我希望在从文本文件中读取的列表框中出现类似的内容:John Doe |97|71|83|丹尼尔·洛佩兹 |99|93|97|简·多伊 |100|100|99|但是我得到了这个: John Doe |97 Daniel Lopez |99 Jane Doe |100 如果我添加一个额外的列变量,它只会将上面的分数替换为它右侧的下一组分数。像这样:John Doe |71 Daniel Lopez |93 Jane Doe |100
  • @ChocolateSnow 这听起来像是一个新问题,所以您应该将它作为一个新问题发布。另外,尽量清楚地表达您的问题,因为您的评论不是很清楚。
【解决方案2】:

就问题而言,当一个列表可能有这么多的字符串表示形式时,编译器怎么会知道如何将字符串转换为列表。如果要这样做,那将是一个非常缓慢的操作。

修复
要修复你的代码,你可以用这个替换你的循环。

while (textIn.Peek() != -1)
{
    string row = textIn.ReadLine();
    StudentClass studentList = new StudentClass();
    int index = row.IndexOf("|");

    //checking that there were some scores
    if (index < 0) {
        studentList.Name = row;
        continue;
    }

    studentList.Name = row.Substring(0, index);
    studentList.Scores =  row.Substring(index + 1).Split('|').Select(int.Parse).ToList();
    students.Add(studentList);
}

但是,即使使用此修复程序也存在许多问题。 如果您要添加另一个由“|”分隔的列表使用这种方法解析会变得越来越困难。

我建议您改用 Json.Net 等更强大和更通用的东西来序列化您的类。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多