C# Linq的Cast()方法 – 将序列中的元素强制转换为指定类型

  • Post category:C#

Cast()是C#中Linq的一个方法,用于将一个集合中的元素转换为指定类型,如果转换失败则会抛出异常。下面是Cast()方法的详细攻略:

标题

C# Linq的Cast()方法

语法

public static IEnumerable<TResult> Cast<TResult>(
    this IEnumerable source
);

参数

  • source:要转换为IEnumerable的元素集合类型
  • TResult:要将元素强制转换的目标类型

返回值

返回经过类型转换后的IEnumerable类型序列

示例1

以下示例展示了如何将一个整数类型的数组转换成一个字符串类型的序列:

int[] arr = { 1, 2, 3, 4, 5 };
IEnumerable<string> strArr = arr.Cast<string>();
foreach (var item in strArr)
{
    Console.WriteLine(item);
}

输出结果为:

1
2
3
4
5

示例2

以下示例展示了如何将一个List的基类类型转换为派生类类型的序列:

class Person
{
    public string Name { get; set; }
}
class Student : Person
{
    public int Score { get; set; }
}

List<Person> list = new List<Person>
{
    new Person { Name = "Amy" },
    new Student { Name = "Bob", Score = 90 }
};
// 转换为Student类型的序列
IEnumerable<Student> students = list.Cast<Student>();
foreach (var item in students)
{
    Console.WriteLine($"{item.Name} {item.Score}");
}

输出结果为:

System.InvalidCastException:“无法将类型“Person”转换为“Student”。”

上面的输出结果是类型转换异常的信息,因为Person类型并不是Student类型的基类,所以无法将Person对象转换为Student对象。

总结

Cast()方法是Linq常用的转换方法,可以将一个集合中的元素转换为指定类型的元素。在使用时需要确保要转换的集合中的元素类型是可以转换为目标类型的,否则会出现类型转换异常。