C # type conversion in. Net)

Source: Internet
Author: User
Tags month name

1. binning, unboxing, or Alias

In many C #. NET books, int-> Int32 is a packing process, and vice versa. The same applies to many other variable types, such as short <-> Int16, long <-> Int64. Generally, programmers do not need to understand this process, because these packing and unpacking actions can be completed automatically without code intervention. However, we need to remember the relationships between these types. Therefore, we use "aliases" to remember the relationships between them.

C # is a fully object-oriented language that is more thorough than Java's object-oriented language-it encapsulates a simple data type into a class through the default packing action. Int32, Int16, Int64, and so on are the corresponding class names, and the familiar and easy-to-remember names, such as int, short, and long, we can call it an alias of the Int32, Int16, Int64, and other types. In addition to the three types, which classes have "alias? The following are commonly used:

Bool-> System. Boolean (Boolean type, its value is true or false)
Char-> System. Char (Bytes type, occupies two bytes, indicating 1 Unicode character)
Byte-> System. Byte (byte, which occupies 1 Byte, indicates an eight-digit positive integer, ranging from 0 ~ 255)
Sbyte-> System. SByte (in byte notation, which occupies 1 byte, indicates an 8-digit integer, range:-128 ~ 127)
Ushort-> System. UInt16 (unsigned short integer, which occupies 2 bytes and represents a 16-bit positive integer in the range of 0 ~ 65,535)
Uint-> System. UInt32 (unsigned integer, 4 bytes, representing a 32-bit positive integer, range: 0 ~ 4,294,967,295)
Ulong-> System. UInt64 (unsigned long integer, which occupies 8 bytes, indicates a 64-bit positive integer in the range of 0 ~ About 10 to the power of 20)
Short-> System. Int16 (short integer, which occupies 2 bytes, indicates a 16-bit integer, range:-32,768 ~ 32,767)
Int-> System. Int32 (integer, 4 bytes, representing a 32-bit integer, ranging from-2,147,483,648 to 2,147,483,647)
Long-> System. Int64 (an integer of 8 bytes, representing a 64-bit integer. The value range is about-(19 of 10) to the 19th power of 10)
Float-> System. Single (Single-precision floating point, 4 bytes)
Double-> System. Double (double-precision floating point type, 8 bytes)

We can use the following code for an experiment:

Private void TestAlias (){
// This. textBox1 is a text box of the System. Windows. Forms. TextBox type.
// The Multiline attribute has been set to true in the design.
Byte a = 1; char B = 'a'; short c = 1;
Int d = 2; long e = 3; uint f = 4; bool g = true;
This. textBox1.Text = "";
This. textBox1.AppendText ("byte->" + a. GetType (). FullName + "\ n ");
This. textBox1.AppendText ("char->" + B. GetType (). FullName + "\ n ");
This. textBox1.AppendText ("short->" + c. GetType (). FullName + "\ n ");
This. textBox1.AppendText ("int->" + d. GetType (). FullName + "\ n ");
This. textBox1.AppendText ("long->" + e. GetType (). FullName + "\ n ");
This. textBox1.AppendText ("uint->" + f. GetType (). FullName + "\ n ");
This. textBox1.AppendText ("bool->" + g. GetType (). FullName + "\ n ");
} Create a button in the form and call the TestAlias () function in its click event. The running result is as follows:

Byte-> System. Byte
Char-> System. Char
Short-> System. Int16
Int-> System. Int32
Long-> System. Int64
Uint-> System. UInt32
Bool-> System. Boolean

This is enough to indicate the classes corresponding to each alias!

2. Mutual conversion between numeric types

The value types mentioned here include byte, short, int, long, fload, and double. According to the order, values of various types can be automatically converted backward. For example, if a short type data value is assigned to an int type variable, the short value is automatically converted to an int type value and then assigned to the int type variable. For example:

Private void TestBasic (){
Byte a = 1; short B = a; int c = B;
Long d = c; float e = d; double f = e;
This. textBox1.Text = "";
This. textBox1.AppendText ("byte a =" + a. ToString () + "\ n ");
This. textBox1.AppendText ("short B =" + B. ToString () + "\ n ");
This. textBox1.AppendText ("int c =" + c. ToString () + "\ n ");
This. textBox1.AppendText ("long d =" + d. ToString () + "\ n ");
This. textBox1.AppendText ("float e =" + e. ToString () + "\ n ");
This. textBox1.AppendText ("double f =" + f. ToString () + "\ n ");
} The translation passes smoothly. The running result is that the values of each variable are 1. Of course, their types are System. Byte ...... System. Double type. Now let's try. What if we reverse the order of values? Append the following statement to the TestBasic () function:

Int g = 1;
Short h = g;
This. textBox1.AppendText ("h =" + h. ToString () + "\ n ");

Result compilation error:
G: \ Projects \ Visual C # \ Convert \ Form1.cs (118): You cannot implicitly Convert the type "int" to "short"
The first line of Form1.cs is the row where short h = g is located.

At this time, if we insist on conversion, we should use forced type conversion, which is often mentioned in C language, that is, "(type name) variable name to forcibly convert data. The preceding example is modified as follows:

Short g = 1;
Byte h = (byte) g; // convert the value of the short Type g to the short type and then assign it to the variable h.
This. textBox1.AppendText ("h =" + h. ToString () + "\ n ");

After compilation, h = 1 is output and the conversion is successful.
However, if we use forced conversion, we have to consider another problem: the short type range is-32768 ~ 23767, while the byte type ranges from 0 ~ 255. What will happen if the variable g size exceeds the byte range? Let's rewrite the code again and change the value to 265, which is 10 larger than 255.

Short g = 265; // 265 = 255 + 10
Byte h = (byte) g;
This. textBox1.AppendText ("h =" + h. ToString () + "\ n ");

There is no compilation error, but the running result is not h = 265, but h = 9.
Therefore, when performing conversion, we should note that the data to be converted cannot exceed the range of the target type. This is not only reflected in the conversion of the Multi-byte data type (relative, short in the above example) to the smaller byte type (relative, byte in the above example, it is also reflected in the conversion of byte 129 to sbyte between the same number of bytes of the signed type and the unsigned type. This example is similar and not detailed.

3. ASCII and Unicode characters

Most of the time, we need to get an ASCII code of an English character, a Unicode code of a Chinese character, or query the encoding of a character from the relevant encoding. Many people, especially those who learn C # From the VB program sequence, complain about why C # does not provide ready-made functions to do this-because there is Asc () in VB () functions and Chr () functions are used for this type of conversion.
However, if you have learned C, you will know that we only need to forcibly convert the English numeric data into appropriate numeric data to get the corresponding ASCII code. Otherwise, if you forcibly convert a suitable numeric data to numeric data, you can get the corresponding characters.
In C #, the character range is extended, including not only single-byte characters, but also double-byte characters, such as Chinese characters. The conversion between characters and encoding is still extended by the C language-forced conversion. Let's take a look at the example below.

Private void TestChar (){
Char ch = 'a'; short ii = 65;
This. textBox1.Text = "";
This. textBox1.AppendText ("The ASCII code of \ '" + ch + "\' is:" + (short) ch + "\ n ");
This. textBox1.AppendText ("ASCII is" + ii. ToString () + ", the char is:" + (char) ii + "\ n ");
Char cn = '中'; short uc = 22478;
This. textBox1.AppendText ("The Unicode of \ '" + cn + "\' is:" + (short) cn + "\ n ");
This. textBox1.AppendText ("Unicode is" + uc. ToString () + ", the char is:" + (char) uc + "\ n ");
} The running result is

The ASCII code of 'A' is: 97
ASCII is 65, the char is:
The Unicode of 'is: 20013
Unicode is 22478, the char is: City

In this example, we can have a very clear understanding-through forced conversion, we can be able to encode or get the characters represented by encoding. If you do not need a short-type encoding, refer to the Code 1st for conversion to obtain the int and other types of encoding values.

4. Conversion between a numeric string and a numeric value

First, we need to understand what a numeric string is. We know that in C #, strings are represented by a pair of double quotation marks containing several characters, such as "123 ". And "123" is relatively special, because the characters that constitute the string are digits, such a string is a numerical string. In our eyes, this is a string of characters and a number, but the computer only considers it as a string, not a number. Therefore, in some cases, we convert a string to a value when entering a value. In other cases, we need to convert the string to a value on the contrary.

It is very easy to convert a value into a string because each class has a void ToString () method. All numeric void ToString () methods can convert data into numeric strings. For example, 123. ToSting () will get the string "123 ".

What should we do if we convert a numeric string into a numeric value? We will find that there is a static Parse () function for values such as short, int, and float. This function is used to convert a string to a corresponding value. Let's take a float type conversion as an example: float f = float. Parse ("543.21"); the result f value is 543.21F. Of course, other numeric types can be converted using the same method. The following example gives a clearer description of the conversion method:

Private void TestStringValue (){
Float f = 54.321F;
String str = "123 ";
This. textBox1.Text = "";
This. textBox1.AppendText ("f =" + f. ToString () + "\ n ");
If (int. Parse (str) = 123 ){
This. textBox1.AppendText ("str convert to int successfully .");
} Else {
This. textBox1.AppendText ("str convert to int failed .");
}
} Running result:

F = 54.321
Str convert to int successfully.

5. Conversion between string and character array

The String class System. String provides a void ToCharArray () method, which can be used to convert strings to character arrays. For example:

Private void TestStringChars (){
String str = "mytest ";
Char [] chars = str. ToCharArray ();
This. textBox1.Text = "";
This. textBox1.AppendText ("Length of \" mytest \ "is" + str. Length + "\ n ");
This. textBox1.AppendText ("Length of char array is" + chars. Length + "\ n ");
This. textBox1.AppendText ("char [2] =" + chars [2] + "\ n ");
} In this example, the length of the converted character array and one of its elements are tested. The results are as follows:

Length of "mytest" is 6
Length of char array is 6
Char [2] = t

It can be seen that the result is completely correct, which indicates that the conversion is successful. In turn, what should we do if we want to convert character arrays into strings?
We can use the constructor of the System. String class to solve this problem. The System. String class has two constructor functions constructed through character arrays, namely, String (char []) and String [char [], int, int ). The latter has two more parameters because it can specify which part of the character array is used to construct the string. The former uses all elements of the character array to construct a string. For example, in the TestStringChars () function, enter the following statement:

Char [] tcs = {'T', 'E','s ', 't', '', 'M', 'E '};
String tstr = new String (tcs );
This. textBox1.AppendText ("tstr = \" "+ tstr +" \ "\ n ");

Enter tstr = "test me" in the running result. The test indicates that the conversion is successful.
In fact, many times we need to convert a string into a character array to obtain a character in the string. For this purpose alone, we do not need to perform conversion by using the [] Operator of System. String. Refer to the following example and add the following language name to the TestStringChars () function:

Char ch = tstr [3];
This. textBox1.AppendText ("\" "+ tstr +" \ "[3] =" + ch. ToString ());

The correct output is "test me" [3] = t. After testing, the output is correct.

6. Conversion between strings and byte Arrays

If you want to find a method in the System. String class to convert the String and byte array, I am afraid you will be disappointed. To perform this conversion, we have to use another class: System. Text. Encoding. This class provides the bye [] GetBytes (string) method to convert a string to a byte array, and the string GetString (byte []) method to convert a byte array to a string.

System. text. the Encoding class does not seem to have any constructors available, but we can find several default Encoding, that is, Encoding. default (get the system's current ANSI code page Encoding), Encoding. ASCII (get the Encoding of the 7-bit ASCII character set), Encoding. unicode (get the Encoding in the Unicode format in the Little-Endian byte order), Encoding. UTF7 (get the Encoding of the UTF-7 format), Encoding. UTF8 (get the encoding of the UTF-8 format) and so on. Here we mainly talk about the difference between Encoding. Default and Encoding. Unicode for conversion.

Encoding. default converts each single-byte character, such as a half-width English character, into one byte, and converts each double-byte character, such as a Chinese character, into two bytes. Encoding. Unicode converts both of them into two bytes. The following describes the conversion methods and the differences between Encoding. Default and Encodeing. Unicode:

Private void TestStringBytes (){
String s = "C # Language ";
Byte [] b1 = System. Text. Encoding. Default. GetBytes (s );
Byte [] b2 = System. Text. Encoding. Unicode. GetBytes (s );
String t1 = "", t2 = "";
Foreach (byte B in b1 ){
T1 + = B. ToString ("") + "";
}
Foreach (byte B in b2 ){
T2 + = B. ToString ("") + "";
}
This. textBox1.Text = "";
This. textBox1.AppendText ("b1.Length =" + b1.Length + "\ n ");
This. textBox1.AppendText (t1 + "\ n ");
This. textBox1.AppendText ("b2.Length =" + b2.Length + "\ n ");
This. textBox1.AppendText (t2 + "\ n ");
}
The running result is as follows. I believe you understand it.

B1.Length = 6
67 35 211 239 209 212
B2.Length = 8
67 0 35 0 237 139 0 138

Converts a byte array to a string using the string GetString (byte []) or string GetString (byte [], int, int) Methods of the Encoding class, the Encoding determines whether to use Encoding. Add the following statement to the TestStringBytes () function as an instance:

Byte [] bs = {97, 98, 99,100,101,102 };
String ss = System. Text. Encoding. ASCII. GetString (bs );
This. textBox1.AppendText ("The string is:" + ss + "\ n ");

The running result is: The string is: abcdef

 

7. Conversion between various numeric types and byte Arrays

In the first article, we can find the number of bytes required for various numeric types to store data. When you convert data of a numeric type to a byte array, the corresponding size of the byte array is obtained. Similarly, You need to convert the byte array to a numeric type, also, the byte array must be larger than the number of bytes of the corresponding value type. The main character of this type of conversion is System. BitConverter. This class provides byte [] GetBytes (...) methods To convert various numeric types into byte arrays. methods such as ToInt32, ToInt16, ToInt64, ToUInt32, ToSignle, and ToBoolean are also provided to convert byte arrays into corresponding numeric types.

This type of conversion is usually used only when more minor encoding/decoding operations are required, so we will not detail it here. We will only introduce the System. BitConverter class to you.

8. Convert to hexadecimal

Any data is saved in binary in the computer. Therefore, the binary system is irrelevant to the data storage and only related to the input and output. Therefore, for hexadecimal conversion, We only care about the results in the string.

The ToString () method can be used to convert a value into a string, but in the above 4th, the result is displayed in decimal. Now we can add some parameters to it to convert it to hexadecimal -- use the ToString (string) method. Here we need a string-type parameter, which is the format specifier. The hexadecimal format specifier is "x" or "X". The difference between the two format specifiers lies in the A-F of six numbers: "x" indicates that a-f is represented by lowercase letters, while "X" indicates that the A-F is represented by uppercase letters. For example:

Private void TestHex (){
Int a = 188;
This. textBox1.Text = "";
This. textBox1.AppendText ("a (10) =" + a. ToString () + "\ n ");
This. textBox1.AppendText ("a (16) =" + a. ToString ("x") + "\ n ");
This. textBox1.AppendText ("a (16) =" + a. ToString ("X") + "\ n ");
} The running result is as follows:

A (10) = 188
A (16) = bc
A (16) = BC

At this time, we may have another requirement, that is, to display the result neatly, we need to control the length of the hexadecimal representation. If the length is not enough, fill it with the leading 0. To solve this problem, we only need to write a number indicating the length after the format specifier "x" or "X. For example, to limit the length to 4 characters, you can write it as "X4 ". In the preceding example, add the following sentence:

This. textBox1.AppendText ("a (16) =" + a. ToString ("X4") + "\ n ");

The output result is a (16) = 00BC.

Now let's talk about how to convert a string that represents a hexadecimal number into an integer. This conversion also requires the Parse () method. Here, I need the Parse (string, System. Globalization. NumberStyles) method. The first parameter is a hexadecimal string, such as "AB" and "20" (32 in decimal format. The second parameter System. Globalization. NumberStyles is an enumeration type, which indicates that the hexadecimal enumeration value is HexNumber. Therefore, if we want to convert "AB" to an integer, we should write: int B = int. parse ("AB", System. globalization. numberStyles. hexNumber), and the final value of B is 171.

9. Conversion between date data and long integer data

Why do we need to convert data of the date type into long integer data? There are many reasons, but I personally often use it for the Date Storage of the database. Since various databases have different definitions and processes for the date type, the definitions of the date type data in different languages are also different, because, I would rather save the converted and grown integer data to the database. Although strings can also be saved, using strings also involves many problems, such as regions. In addition, it requires more space than saving long integer data.

Data of the date type should also be converted to long integer data During computation in C. Its long integer value is a number represented at an interval of January 1, 0001 milliseconds since midnight, January 1, 100. This number is called Ticks (scale) in the DateTime of C ). The DateTime type has a read-only attribute named Ticks, which stores the value. In this way, it is very easy to get the long value from a DataTime data type. You only need to read the Ticks value of the DataTime object, for example:

Long longDate = DateTime. Now. Ticks;

The DateTime constructor also provides the corresponding function for constructing DateTime-type data from long integer data: DateTime (long ). For example:

DateTime theDate = new DateTime (longDate );

However, this is a difficult problem for many VB6 programmers, because the date data in VB6 is represented in Double, after converting it to a long integer, only the date is obtained, and there is no time. How can we coordinate these two date types?
System. DateTime provides the double ToOADate () and static DateTime FromOADate (double) functions to solve this problem. The former outputs the current object according to the original double value, and the latter obtains a System. DateTime object from a double value. Example:

Private void TestDateTimeLong (){
Double doubleDate = DateTime. Now. ToOADate ();
DateTime theDate = DateTime. FromOADate (doubleDate );
This. textBox1.Text = "";
This. textBox1.AppendText ("Double value of now:" + doubleDate. ToString () + "\ n ");
This. textBox1.AppendText ("DateTime from double value:" + theDate. ToString () + "\ n ");
}
Running result:

Double value of now: 37494.661541713
DateTime from double value: 2002-8-26 15:52:37

10. Format date data

During programming, the date data is usually output in a certain format. Of course, the output result must be a string. Therefore, we need to use the ToString () method of the System. DateTime class and specify the format string for it. In MSDN, The System. Globalization. DateTimeFormatInfo class provides a very detailed description of the mode string. Therefore, here I only describe some common formats. First, see the following table:

D
One day in the month
One-digit date without leading zero

Dd
One day in the month
A single-digit date has a leading zero

Ddd
Abbreviated name of a day in the middle of the week
Defined in AbbreviatedDayNames

Dddd
Full name of a day in the middle of the week
Defined in DayNames

M
Month number
One-digit month has no leading zero

MM
Month number
A single-digit month has a leading zero.

MMM
Abbreviated month name
Defined in AbbreviatedMonthNames

MMMM
Complete month name
Define in MonthNames

Y
Year that does not contain the epoch
If the year that does not contain the epoch is less than 10, the year that does not have the leading zero is displayed.

Yy
Year that does not contain the epoch
If the year that does not contain the epoch is less than 10, the year with the leading zero is displayed.

Yyyy
Includes the four-digit year of the epoch.


H
12-hour
One-digit hours do not have a leading zero

Hh
12-hour
One-digit hours have a leading zero

H
Hour in 24-hour format
One-digit hours do not have a leading zero

HH
Hour in 24-hour format
One-digit hours have a leading zero

M
Minutes
One-digit minutes without leading zero

Mm
Minutes
The number of minutes in a single digit has a leading zero.

S
Seconds
One-digit seconds without leading zero

Ss
Seconds
The number of seconds in a single digit has a leading zero.

To facilitate your understanding, try the following program:

Private void TestDateTimeToString (){
DateTime now = DateTime. Now;
String format;
This. textBox1.Text = "";
Format = "yyyy-MM-dd HH: mm: ss ";
This. textBox1.AppendText (format + ":" + now. ToString (format) + "\ n ");
Format = "yy-M-d ";
This. textBox1.AppendText (format + ":" + now. ToString (format) + "\ n ");
}
This program will output the results:

Yyyy-MM-dd HH: mm: ss: 2002-08-26 17:03:04
Yy-M-D: 02-8-26

At this time, another problem occurs. What if the text to be output contains format characters? For example

Format = "year: yyyy, month: MM, day: dd ";
This. textBox1.AppendText (now. ToString (format) + "\ n ");

Output:

2ear: 2002, 4 on, 5: 08, 26a2: 26

This is not the result I want. What should I do? There is a way --

Format = "\" year \ ": yyyy, \ 'month \ ': MM, \ 'day \': dd ";
This. textBox1.AppendText (now. ToString (format) + "\ n ");

Check that the running result is correct:

Year: 2002, month: 08, day: 26

We can see that you only need to enclose text information with single or double quotation marks.

Related Article

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.