你可以使用Array.ConvertAll方法。
示例:
int[] iBuf = new int[2]
...
short[] sBuf = Array.ConvertAll(iBuf, input => (short) input)
这个方法需要一个输入数组和一个转换器,结果将是你想要的数组。
编辑:
更短的版本是在ConvertAll中使用现有的Convert.ToInt16方法。
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;
}
回答实际问题... 不,必须涉及循环以将所有值转换。你可以编写自己的程序或者使用已经构建好的方法。