How to: Return the stronger type array using Visual C # .NET TOARRAY (Type)

xiaoxiao2021-03-06  62

The release number of this article has been CHS312390

For Microsoft Visual Basic .NET versions of this article, see

312389.

This task content

summary

Step-by-step example

Summary This article describes how to use Visual C # .NET

TOARRAY (TYPE) method Returns a strong type of array.

ArrayList

TOARRAY method returns

An array of Object types. can not be used

TOARRAY is not parametric implementation

The Object array is converted to the array type you want. For example, if you add some Customer objects to

In ArrayList, the base list cannot be changed to the Customer array. This will result in failure of the following statements and happen to occur:

Customer [] Customer = (Customer []) MyArrayList.toArray (); To return to the strong type array, use the object type as a parameter to accept

TOARRAY overload method. For example, the following statement can be successfully performed:

Customer [] Customer = (Customer []) MyArrayList.toArray (TypeOf (Customer);

Remarks: C # does not allow implicit conversion, so you must explicitly convert

The result of the ToArray method.

important:

All elements of ArrayList must be the same object type. If you will contain a heterogeneous object

ArrayList is converted to a specific type, then

The ToArray method will fail.

Back to top

Step-by-step example

Start a new console application project in Visual C # .NET. Replace the code in class1.cs to the following code: 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;

}

Press CTRL F5 combination to generate and run the project. (Ctrl F5 Combined Key Allows the console window to keep open state.) To recover INVALIDCASTEXCEPTION, follow the two annotations in the sample code. Back to top

The information in this article applies to:

Microsoft Visual C # .NET (2002)

Recent Updated: 2002-2-24 (1.0) Keyword Kbhowto KbhowTomaster KB312390

转载请注明原文地址:https://www.9cbs.com/read-109038.html

New Post(0)