[英]Converting a string array into a short array
I have a string array to be defined by user input and I need to convert the string array into a short array so I can use the values for calculations. 我有一个要由用户输入定义的字符串数组,我需要将字符串数组转换为短数组,以便可以将这些值用于计算。 I need to use an array because I will need to refer to all of the values collectively later.
我需要使用一个数组,因为稍后需要集体引用所有值。 This is what I have:
这就是我所拥有的:
string [] calIntake = new string[3];
calIntake [0] = Console.ReadLine ();
calIntake[1] = Console.ReadLine ();
calIntake[2] = Console.ReadLine ();
I have tried: 我努力了:
short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), Short.Parse);
I get an error with this that says: "The type arguments for method 'System.Array.ConvertAll(TInput[], System.Converter)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 我收到这样的错误消息:“无法从用法中推断出方法'System.Array.ConvertAll(TInput [],System.Converter)'的类型参数。尝试显式指定类型参数。
Then I tried: 然后我尝试了:
short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), ne Converter<string, short>(Short.Parse));
and I get the same error. 和我得到同样的错误。 So how can I convert a string array based on user input into a short array?
那么如何将基于用户输入的字符串数组转换为短数组呢?
您可以通过short.Parse
方法投影字符串:
short[] calIntakeNum = calIntake.Select(short.Parse).ToArray();
calIntake
is already an array, you don't need to Split
it. calIntake
已经是一个数组,您不需要Split
它。 There is no type Short
in C#, there is short
or Int16
C#中没有类型
Short
,没有short
或Int16
short[] calIntakeNum = Array.ConvertAll(calIntake, short.Parse);
The second method you tried failed because you tried calling a method on a class that doesn't exist, and because Short.Parse
doesn't exist. 您尝试的第二个方法失败是因为您尝试在不存在的类上调用方法,并且因为
Short.Parse
不存在。 Removing the .split(',')
from your first parameter to ConvertAll
and changing Short.Parse
to short.Parse
will fix the issue: 从第一个参数中将
.split(',')
删除为ConvertAll
并将Short.Parse
更改为short.Parse
将解决此问题:
short[] calIntakeNum = Array.ConvertAll(calIntake, new Converter<string, short>(short.Parse));
If it's possible for your program, you could declare your array as short[]
originally, and call short.Parse
on Console.ReadLine()
: 如果您的程序可行,则可以将数组最初声明为
short[]
,然后在Console.ReadLine()
上调用short.Parse
:
short[] shortArray = new short[3];
shortArray[0] = short.Parse(Console.ReadLine());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.