我有一个 value 的字符串{} "[1, 2, 3, 4]"。我想将其转换为列表。
这是我尝试过的:
char[] delimiterChars = { '[', ',', ']' };
string text = "[1, 2, 3, 4]";
text = text.Replace("[", "");
text = text.Replace("]", "");
List<int> numbers = new List<int>( Array.ConvertAll(text.Split(delimiterChars ), int.Parse) );
System.Console.WriteLine($"{numbers}");
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
System.Reflection.TargetInvocationException:调用的目标已抛出异常。---> System.FormatException: 输入字符串的格式不正确。
我的预期输出是[1, 2, 3, 4].
请指教。
对我来说看起来像 json ......
using Newtonsoft.Json;
string text = "[1, 2, 3, 4]";
List<int> numbers = JsonConvert.DeserializeObject<List<int>>(text);
Run Code Online (Sandbox Code Playgroud)
虽然说实话,你使用的是字符串常量......所以......
List<int> numbers = new List<int>() {1, 2, 3, 4};
Run Code Online (Sandbox Code Playgroud)
也能正常工作。