C#反转字符串调用Reverse报CS0411类型参数无法推断错误如何解决
C#字符串反转编译错误CS0411问题原因及解决方案
错误信息:
Main.cs(8,39): error CS0411: The type arguments for method `System.MemoryExtensions.Reverse<T>(this System.Span<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly
错误产生原因
- 当前代码没有引入
System.Linq命名空间,编译器调用Reverse方法时匹配到了System.MemoryExtensions下针对Span<T>的泛型Reverse方法,该方法不适用于string类型的直接调用,无法自动推断泛型参数,因此抛出编译错误。 - 你原本预期调用的
Reverse是LINQ提供的针对IEnumerable<T>的扩展方法,string本身实现了IEnumerable<char>,引入LINQ命名空间后就能正常匹配到对应方法。
解决方案
方案1:引入LINQ命名空间
在代码开头添加using System.Linq;即可,修改后完整代码如下:
using System; using System.Linq; class MainClass { public static string FirstReverse(string str) { string backwards = new string(str.Reverse().ToArray()); return backwards; } static void Main() { Console.WriteLine(FirstReverse(Console.ReadLine())); } }
方案2:不使用LINQ的实现方式
如果不想引入LINQ,也可以直接操作字符数组完成反转,不需要额外依赖命名空间,代码如下:
using System; class MainClass { public static string FirstReverse(string str) { char[] charArr = str.ToCharArray(); Array.Reverse(charArr); return new string(charArr); } static void Main() { Console.WriteLine(FirstReverse(Console.ReadLine())); } }
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

