如何将int []转换为short []?

Hoo*_*ony 3 c# arrays type-conversion

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  
Run Code Online (Sandbox Code Playgroud)

结果与我想要的不同.
有没有使用循环转换的方法?

Mil*_*ter 6

您可以使用Array.ConvertAll方法.

例:

int[]   iBuf = new int[2];
  ...
short[] sBuf = Array.ConvertAll(iBuf, input => (short) input);
Run Code Online (Sandbox Code Playgroud)

此方法采用输入数组和转换器,结果将是您想要的数组.

编辑:更短的版本是使用现有的Convert.ToInt16方法.在ConvertAll里面:

int[] iBuf = new int[5];
short[] sBuf = Array.ConvertAll(iBuf, Convert.ToInt16);
Run Code Online (Sandbox Code Playgroud)

那么,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;
}
Run Code Online (Sandbox Code Playgroud)

要回答实际问题......不,在某些时候,将涉及转换所有值的循环.您可以自己编程,也可以使用已构建的方法.