我有一个由用户输入定义的字符串数组,我需要将字符串数组转换为短数组,以便我可以使用这些值进行计算。我需要使用数组,因为我需要稍后集体引用所有值。 这就是我所拥有的:
short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), Short.Parse);
我试过了:
short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), ne Converter<string, short>(Short.Parse));
我得到一个错误,上面写着:“方法'System.Array.ConvertAll(TInput [],System.Converter)的类型参数'无法从用法中推断出来。请尝试明确指定类型参数。
然后我尝试了:
{{1}}
我得到同样的错误。那么如何将基于用户输入的字符串数组转换为短数组呢?
答案 0 :(得分:2)
您可以通过short.Parse
方法投射字符串:
short[] calIntakeNum = calIntake.Select(short.Parse).ToArray();
答案 1 :(得分:1)
calIntake
已经是一个数组,您不需要Split
它。 C#中没有Short
类型,有short
或Int16
short[] calIntakeNum = Array.ConvertAll(calIntake, short.Parse);
答案 2 :(得分:0)
您尝试的第二种方法失败了,因为您尝试在不存在的类上调用方法,并且因为Short.Parse
不存在。将.split(',')
从您的第一个参数移至ConvertAll
并将Short.Parse
更改为short.Parse
将解决此问题:
short[] calIntakeNum = Array.ConvertAll(calIntake, new Converter<string, short>(short.Parse));
如果你的程序可以,你可以最初将你的数组声明为short[]
,并在short.Parse
上致电Console.ReadLine()
:
short[] shortArray = new short[3];
shortArray[0] = short.Parse(Console.ReadLine());