本文的发布号曾为 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 方法会失败。
返回页首
分步示例
- 在 Visual C# .NET 中启动一个新的控制台应用程序项目。
- 将 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; }
- 按 CTRL+F5 组合键生成并运行该项目。 (CTRL+F5 组合键允许控制台窗口保持打开状态。)
- 若要复现 InvalidCastException 异常,请按照示例代码中的两条注释说明操作。 返回页首
这篇文章中的信息适用于:
- Microsoft Visual C# .NET (2002)
最近更新: | 2002-2-24 (1.0) |
关键字 | kbhowto kbHOWTOmaster KB312390 |