【问题标题】:Invalid expression term '[' using c# [closed]使用c#的无效表达式术语'[' [关闭]
【发布时间】:2021-03-04 10:47:38
【问题描述】:

谁能帮我看看我的代码有什么问题。我正在尝试将 JavaScript 代码转换为 C# 代码

public class SplitString
{
  public static string[] Solutions(string str)
  {
    arr = [];
    for(var i = 0; i < str.Length; i += 2){
      second = str[i+1] || '_';
      arr.push(str[i] + second);
    }
    return arr;
    
  }
}

我遇到了这个错误

src/Solution.cs(5,11): 错误 CS1525: 无效的表达式术语 '[' src/Solution.cs(5,12):错误 CS0443:语法错误;期望值

【问题讨论】:

  • 恐怕你需要学习一点 C# 语法。 arr = [] 不是有效的 C#,array.push 在 C# 中不存在,仅举两个例子
  • 感谢@canton7 的回复。我正在尝试将此代码列表转换为 c# 你能帮帮我吗,我真的需要它。 link
  • 它是做什么的second = str[i+1] || '_';
  • @Noyti 如果你真的需要它,那么你将不得不了解原始代码做什么,并转换intent,不是代码直接
  • SO 没有代码翻译服务。要翻译代码并确保它做正确的事情,您只需要能够编写和阅读 c# 和 javascript。现在好像你不懂c#。为了解决这个问题,开始学习它,在接下来的几周内完成几个教程。

标签: javascript c#


【解决方案1】:

javascript和C#是完全不同的语言; .NET / C# 数组是固定大小的 - 所以,您可能需要一个列表:

var arr = new List<string>();
for(var i = 0; i < str.Length; i += 2){
  var second = str[i+1]; // || '_'; <== this on the right makes no sense in C#
  arr.Add(str[i] + second);
}
return arr.ToArray();

【讨论】:

  • 我遇到这个错误:src/Solution.cs(5,19): error CS0246: The type or namespace name 'List&lt;&gt;' could not be found (are you missing a using directive or an assembly reference?)
  • @Noyti 您需要通过文件顶部的using System.Collections.Generic; 导入System.Collections.Generic
  • @Noyti Anotehr 每个 C# 程序员都知道的例子。您需要完整的教程,而不是Stack Overflow 答案
猜你喜欢
  • 1970-01-01
  • 2011-06-22
  • 2020-09-23
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-03
  • 2019-06-10
  • 1970-01-01
相关资源
最近更新 更多