在LINQ中,CAST运算符用于将集合中存在的所有元素强制转换/转换为新集合的指定数据类型。如果我们尝试强制转换/转换集合中不同类型的元素(字符串/整数),则转换将失败,并且将抛出异常。
C#代码
IEnumerable<string> result = obj.Cast<string>();
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //create an object named 'obj' of ArrayList ArrayList obj = new ArrayList(); //assign the values to the object 'obj' obj.Add("USA"); obj.Add("Australia"); obj.Add("UK"); obj.Add("India"); //Here we are converting the ArrayList object to String type of object and store the result in 'result' IEnumerable<string> result = obj.Cast<string>(); //Now with the help of foreach loop we will print the value of result foreach (var item in result) { Console.WriteLine(item); } Console.ReadLine(); } } }
输出:
在上面的示例中,我们有一个Arraylist,我们在其中添加了几个国家/地区。这些国家/地区是一种对象类型,通过使用强制转换运算符,我们将ArrayList对象转换为字符串类型对象。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)