int[] iBuf = new int[2];
iBuf[0] = 1;
iBuf[1] = 2;
short[] sBuf = new short[2];
Buffer.BlockCopy(iBuf, 0, sBuf, 0, 2);
result
iBuf[0] = 1
sBuf[0] = 1
iBuf[1] = 2
sBuf[1] = 0
My desired result
iBuf[0] = 1
sBuf[0] = 1
iBuf[1] = 2
sBuf[1] = 2
结果和我想要的不一样。
有没有不使用循环的转换方法?
最佳答案
您可以使用 Array.ConvertAll 方法。
例子:
int[] iBuf = new int[2];
...
short[] sBuf = Array.ConvertAll(iBuf, input => (short) input);
此方法接受一个输入数组和一个转换器,结果将是您想要的数组。
编辑: 一个更短的版本是使用现有的 Convert.ToInt16 方法。在 ConvertAll 里面:
int[] iBuf = new int[5];
short[] sBuf = Array.ConvertAll(iBuf, Convert.ToInt16);
那么,ConvertAll 是如何工作的?让我们看一下实现:
public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (converter == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.Ensures(Contract.Result<TOutput[]>() != null);
Contract.Ensures(Contract.Result<TOutput[]>().Length == array.Length);
Contract.EndContractBlock();
TOutput[] newArray = new TOutput[array.Length];
for (int i = 0; i < array.Length; i++)
{
newArray[i] = converter(array[i]);
}
return newArray;
}
要回答实际问题...不,在某些时候会涉及一个循环来转换所有值。您可以自己编程或使用已经构建的方法。
关于c# - 如何将 int[] 转换为 short[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44303122/