. NET Framework conversion methods (C #)

Source: Internet
Author: User

Various types of conversion methods in the. NET framework can be described as varied. Here, various types of conversion are summarized as follows (take C # as an example ):

I. type conversion of a single variable:

1 unforced type conversion:

Unless otherwise stated, the compiler will automatically complete the conversion, such as int A = 0; float B = A; double C = B;

2 forced type conversion:

A forced type specifier must be added; otherwise, compilation fails, for example, double C = 0.0; float B = (float) C; int A = (INT) B;

3 parse and tostring methods:

Converts data types and strings. Most data types cannot be obtained by forcibly converting the string type, such as string S = "123"; int A = (INT) s; this will cause a compilation error, because the string type cannot be forcibly converted to int. However, you can use the parse method to do this, for example, int A = int. parse (s );. Most basic value types have the parse method, but none of the reference types are available. However, although not all types can be converted from strings, all types can be converted to strings, because all types have the tostring method. For example, int A = 123; string S = A. tostring ();

By the way, parse is a strict method. As long as the string format is incorrect, it will throw an exception, such as Int. parse ("123.0"), or Int. parse ("123,45") will throw an exception. Solution: If it is "123.0" or the like, first parse into a floating point number, and then forcibly convert the type into an integer. If it is "", you can use the string spilt method to split the string, then, parse each split string separately to obtain an int Array }.

In addition, the string. Format method provides richer formats for converting numeric values into strings.

4 convert class

The system. Convert class can convert each basic data type. For example:

Int A = convert. toint32 ("123 ");

String S = convert. tostring ();

Int B = convert. changetype ("123", typeof (INT ));

However, the convert class only provides conversion between basic data types, and does not provide conversion between container (such as array) Types and custom types. If you want to convert custom data types to basic data types, you must implement the iconvertible interface.

5 typeconverter

System. componentmodel. the typeconverter class provides the base classes for various types of converters. However, you should not construct instances of this class or its derived classes, instead, use system. componentmodel. the getconverter method of typedescriptor is used to obtain the converter and then convert the converter. As shown below:CodeConvert the string "red" to a red color:

Color c = (color) typedescriptor. getconverter (typeof (color). convertfromstring ("red ");

For custom types, you can implement conversion by inheriting the typeconverter class. This is the final method. It can implement mutual conversion between any two types. The specific implementation is complicated, I won't talk about it here. For more information, see

MS-help: // Ms. VSCC. v90/ms. msdnqtr. v90.chs/fxref_system/html/35bffd5f-b9aa-1ccd-99fe-b0833551e562.htm

6 xmlreader class

The system. xml. xmlreader class can convert text to various basic data types, including array types, but it is troublesome to convert text into XML format first. Use the following code to convert text to a double array:

Xmlreader xr = xmlreader. Create ("E: // 1.xml ");
XR. movetocontent ();
Double [] B = (double []) XR. readelementcontentas (typeof (double []), null );
Of course, if you want to make an XML file in the E drive, you can do this:

123 1.2 4.2 5.6 57.5

That is to say, add And You can replace root with any other string. Save the file name in notepad with the suffix XML.

2. Mutual conversion between containers (without changing the type of container elements)

1 Constructor

Many constructor functions can input values of another container, such as the new list (New int [] {}) constructs a new list using an int array as a parameter. Generic classes. In fact, containers that implement the ienumerable interface can convert each other in this way.

2 copyto, toarray, tolist Function

All containers that implement the icollection interface can copy data to an array using the copyto method. If you implement the ienumerable interface, you can use toarray and tolist to copy the data in the container to an array or list,

3 Conversion between two-dimensional arrays (or multi-dimensional arrays) and other containers

. By default, two-dimensional arrays in the net framework cannot be converted to one-dimensional arrays or other containers, but they can be converted indirectly. The oftype extension method can be used to convert two-dimensional arrays to ienumerable, then, from the toarray of ienumerable, tolist can be converted to a one-dimensional array or list. The following code converts a two-dimensional array into a one-dimensional array:

Int [,] array2 = {1, 2}, {1, 2 }};
Int [] array1 = array2.oftype (). Toarray ();
In fact, the true purpose of oftype is to filter out some elements of a specific type, and all elements are actually selected here.

Type conversion of elements in three containers

1 cast

This method can be used by any container that implements the ienumerable interface. For example, convert an integer array to a string array:

Int [] array1 = {1, 2, 3 };

Ienumerable Array2 = array1.cast ()

Or string [] array2 = array1.cast (). Toarray ();

However, the cast method is only limited to forced type conversion and non-forced type conversion. The preceding parse, convert, and typeconverter methods cannot be used, for example, you cannot use cast to convert a string array to an integer array.

2 select

In principle, this method can complete any conversion. For example, convert a string array to an integer array:

String [] S = {"1", "2", "3 "};
Int [] I = (S. Select (x => Int. parse (x). toarray ());
Or int [] I = (S. Select (x => convert. toint32 (x). toarray ());

Or int [] I = (S. Select (x => (INT) typedescriptor. getconverter (typeof (INT). convertfrom (X). toarray ();

Lambda expressions are used here.

3 arraylist

System. collections. arraylist is a class that can accommodate any type of elements. To implement element conversion, You can first copy the elements of the container to the arraylist, and then copy the elements of the arraylist to another type of container, it automatically completes type conversion. For example, convert an integer array to a string array:

Int [] array1 = {1, 2, 3 };

Arraylist array2 = new arraylist (array1 );

String [] array3 = array2.toarray (typeof (string ));

The disadvantage of this method is similar to cast, that is, only forced type conversion and non-forced type conversion are limited.

 

(Solemnly declare: hereArticleFor reprinting, not original !)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.