C# 数组 - ConvertAll() 方法
C# 数组 ConvertAll() 方法用于使用指定的转换函数将一种类型的数组转换为另一种类型的数组。
让我们看看一篇与 ConvertAll 方法相关的文章:C# 程序将整数数组转换为字符串数组。
异常
如果数组为 null 或转换器为 null,此方法将抛出 ArgumentNullException。
语法
以下是 C# 数组 ConvertAll() 方法的语法 -
public static TOutput[] ConvertAll<TInput,TOutput> (TInput[] array, Converter<TInput,TOutput> converter);
在上述语法中,TInput 和 TOutput 分别是源数组和目标数组。
参数
此方法接受以下参数 -
- array:一个从零开始的一维数组,用于转换为目标类型。
- converter:一个转换器,用于将每个元素从一种类型转换为另一种类型。
返回值
此方法返回一个目标类型的数组,其中包含从源数组转换后的元素。
示例 1:将整数转换为字符串
让我们看一个使用 CovertAll() 方法将整数转换为字符串的基本示例 -
using System; class Program { static void Main() { int[] numbers = { 1, 2, 3, 4, 5 }; string[] strings = Array.ConvertAll(numbers, num => num.ToString()); Console.WriteLine("Converted to strings:"); foreach (string str in strings) { Console.WriteLine(str); } } }
输出
以下是输出 -
Converted to strings: 1 2 3 4 5
示例 2:将字符串转换为整数
让我们看另一个使用 ConvertAll() 方法将字符串数组转换为整数数组的示例 -
using System; class Program { static void Main() { string[] stringNumbers = { "10", "20", "30", "40" }; int[] integers = Array.ConvertAll(stringNumbers, str => int.Parse(str)); Console.WriteLine("Converted to integers:"); foreach (int number in integers) { Console.WriteLine(number); } } }
输出
以下是输出 -
one, two, three changed, two, three
示例 3:将自定义对象转换为其他类型
在此示例中,我们使用 ConvertAll() 方法将自定义对象转换为其他类型 -
using System; class Person { public string Name { get; set; } } class Program { static void Main() { Person[] people = { new Person { Name = "Aman" }, new Person { Name = "Kumar" }, new Person { Name = "Gupta" } }; string[] names = Array.ConvertAll(people, person => person.Name); Console.WriteLine("Converted to names:"); foreach (string name in names) { Console.WriteLine(name); } } }
输出
以下是输出 -
Converted to names: Aman Kumar Gupta
示例 4:将双精度型转换为整数
由于我们已经将字符串转换为整数,反之亦然,因此在本例中,我们使用 ConvertAll() 方法将双精度型转换为整数 -
using System; class Program { static void Main() { double[] doubleArray = { 1.5, 2.6, 3.7, 4.8 }; int[] intArray = Array.ConvertAll(doubleArray, dbl => (int)Math.Round(dbl)); Console.WriteLine("Converted to integers (rounded):"); foreach (int number in intArray) { Console.WriteLine(number); } } }
输出
以下是输出 -
Converted to integers (rounded): 2 3 4 5