HOW TO: 使用 Visual C# .NET 的 ToArray(type) 方法返回强类型数组
察看本文应用于的产品文章编号 | : | 312390 |
最后修改 | : | 2002年2月24日 |
修订 | : | 1.0 |
本文的发布号曾为 CHS312390
本页概要
本文介绍如何使用 Visual C# .NET 的
ToArray(type) 方法返回强类型数组。
ArrayList 类的无参数的
ToArray 方法返回
Object 类型的数组。 不能使用
ToArray 的无参数的实现将
Object 数组转换为您所希望的数组类型。 例如,如果将一些 Customer 对象添加到
ArrayList 中,基础列表不能变为 Customer 数组。 这将导致以下语句失败,并发生 System.InvalidCastException 异常:
Customer [] customer = (Customer[])myArrayList.ToArray();
若要返回强类型数组,使用将对象类型作为参数来接受的
ToArray 重载方法。 例如,以下语句可以成功执行:
Customer [] customer = (Customer[])myArrayList.ToArray(typeof(Customer));
备注: C# 不允许隐式转换,因此必须显式转换
ToArray 方法的结果。
重要说明:
ArrayList 的所有元素都必须是同一对象类型。 如果将包含异类对象的
ArrayList 转换为特定类型,则
ToArray 方法会失败。
分步示例
1. | 在 Visual C# .NET 中启动一个新的控制台应用程序项目。 |
2. | 将 Class1.cs 中的代码替换为以下代码: using System;using System.Collections;class Class1{[STAThread]static void Main(string[] args){customer c = new customer();c.cname = "anonymous";ArrayList al=new ArrayList();al.Add(c);object[] cArray = al.ToArray();//Display the type of the ArrayList.Console.WriteLine(cArray.GetType());//Uncomment the next line to reproduce the InvalidCastException.//customer[] custArray = (customer[])(al.ToArray());//Comment the next line to reproduce the InvalidCastException.customer[] custArray = (customer[])al.ToArray(typeof(customer));Console.WriteLine(custArray.GetType());}}class customer{public string cname;} |
3. | 按 CTRL+F5 组合键生成并运行该项目。 (CTRL+F5 组合键允许控制台窗口保持打开状态。) |
4. | 若要复现 InvalidCastException 异常,请按照示例代码中的两条注释说明操作。 |