ToArray(type) 方法返回强类型数组

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 异常,请按照示例代码中的两条注释说明操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值