【问题标题】:C#: Cannot implicitly convert type 'System.Collections.Generic.List<char>' to 'System.Collections.Generic.List<string>'C#:无法将类型“System.Collections.Generic.List<char>”隐式转换为“System.Collections.Generic.List<string>”
【发布时间】:2020-06-16 04:54:43
【问题描述】:

我想做某种控制台框架,为此我需要命令和命令的参数。这是我的代码的一部分:

string str = "I do not know how to fix this problem";
List<string> substringList = str.Split().ToList();
List<string> allArgsExcept1st = str[1..^0].ToList();

输入是类型string。 第三行抛出错误:

无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”。

我是 C# 新手,所以我不知道如何看待这个错误以及如何修复它。

谢谢。

【问题讨论】:

  • @Maddy 这个答案还不是很有用。缺少重要的上下文,并且可能会改变该答案是否相关
  • @maccettura,完全同意,但如果用户发现它的信息,则排序跳枪
  • 很公平!我只是不想过早地被标记为欺骗
  • 你的意思是var allArgsExcept1st = substringList.Skip(1);?为什么要将所有内容都转换为List

标签: c# list type-conversion


【解决方案1】:

根据您的最新编辑:

string str = "I do not know how to fix this problem";
List<string> substringList = str.Split().ToList();
List<string> allArgsExcept1st = str[1..^0].ToList();

你的问题在这里:

str[1..^0].ToList()

当您在 string 上使用范围/切片函数 ([1..^0]) 时,您将获得一个 string 作为回报。所以在string 上调用ToList() 会给你一个List&lt;char&gt;(因为string 也是一个IEnumerable&lt;char&gt;)但是你将它分配给一个List&lt;string&gt;

不清楚您最终要在这里做什么,但要解决您的问题,您只需将最后一行更改为:

List<char> allArgsExcept1st = str[1..^0].ToList();

【讨论】:

  • 我没有投反对票,但我怀疑这隐藏了错误而不是修复它。
  • @DourHighArch 是的,我可以看到。我借此机会向 OP 教授关于字符串是 IEnumerable 的切片代码的含义。 OP 没有提供太多细节,所以在他们提供之前我无法提供更好的反馈。但是我仍然认为我的答案实际上是一个正确的答案,并且 OP 的问题在技术上仍然符合标准,所以 idk
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多