Array.ConvertAll<TInput, TOutput> 数组相互转化方法

有个需求,把char数组转换为int数组,然后噼里啪啦就弄了这样一堆代码(辣鸡代码,自己看着都恶心);

 public static int[] CharArrToIntArr(char[] charArr)
        {
            int[] ints = new int[charArr.Length];
            for (int i = 0; i < charArr.Length; i++)        //技术债务:与float转换数组应该可以提取成一个方法
            {
                ints[i] = (int)charArr[i];
            }
            return ints;
        }

方法用途:将一种类型的数组转换为另一种类型的数组,比如讲char[] 数组转化为int[] 数组。

类型参数

TInput: 源数组元素的类型。
TOutput: 目标数组元素的类型。
示例代码:
将char 数组转换为int 数组
            char[] charArray = new char[] { 'a', 'b', 'c' };
            foreach (char item in charArray)
            {
                Console.WriteLine(item.ToString());
            }
            int[] intArray = Array.ConvertAll<char, int>(charArray, value => Convert.ToInt32(value));
            foreach (int item in intArray)
            {
                Console.WriteLine(item.ToString());
            }        

  

猜你喜欢

转载自www.cnblogs.com/Rawls/p/10896173.html