Type conversion in C # .NET

xiaoxiao2021-03-20  197

Recently, due to the needs of programming, some research on C # type conversion, its contents involve C # pack box / unpack / alias, numerical types of mutual conversion, character's ASCII code, and Numeric strings, and numerical values Conversion, string and character array / byte arrays, conversion between various numeric types, and byte arrays, hexadecimal outputs and some conversion processing of date-type data, sharing with you here -

1. Pack, unpacking or alias

Many C # .NET books have an introduction Int-> int32 is a packing process, and it is the process of unboxing. The same is true for many other variables, such as Short <-> INT16, long <-> int64, etc. For general programmers, it is great to understand this process because these packing and unpacking actions can be done automatically, and do not need to write code for intervention. But we need to remember the relationship between these types, so we use "alias" to remember the relationship between them.

C # is the language of the full-to-object, completely thorough than Java-oriented object - it puts the simple data type through the default packing action into a class. INT32, INT16, INT64, etc., the corresponding class name, and those we are familiar, simple and easy to book, such as int, short, long, etc., we can call it as an alias such as int32, int16, int64.

So in addition to these three types, what kinds of "alias" are there? Commonly used some:

Bool -> System.Boolean (Boolean, its value is True or false)

Char -> system.char (character type, two bytes, indicating 1 Unicode character)

BYTE -> System.byte (byte, 1 byte, indicating 8 positive integers, range 0 ~ 255)

Sbyte -> system.sbyte (with symbolic byte, 1 byte, indicating 8-bit integer, range -128 ~ 127)

Ushort -> system.uint16 (no symbol short integer, 2 bytes, represent 16 positive integers, range 0 ~ 65, 535)

UINT -> System.uint32 (no symbol integer, 4 bytes, represent 32 positive integers, range 0 ~ 4, 294, 967, 295)

Ulong -> system.uint64 (no sign long integer, 8 bytes, indicating 64-bit positive integers, 20 to about 10)

Short -> System.Int16 (short integer, 2 bytes, 16-bit integer, range -32, 768 ~ 32, 767)

Int -> System.Int32 (integer, 4 bytes, representing 32-bit integers, range -2, 147, 483, 648 to 2, 147, 483, 647)

Long -> System.Int64 (long integer, 8 bytes, indicating 64-bit integers, scope - (19) (19) times to 10 in 19)

Float -> system.single (single precision floating point, 4 bytes)

Double -> system.double (double precision floating point, 8 bytes)

We can use the following code to make an experiment:

PRIVATE VOID TESTALIAS () {

// this.TextBox1 is a text box, the type is system.windows.forms.textbox // design has set its multiline property to True

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, we will see that the results of the operation are 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 illustrate the corresponding classes of each other!

2. Mutual conversion between numerical types

The numerical types mentioned here include Byte, Short, Int, long, fload, double, etc., according to this order, various types of values ​​can be automatically converted later. For example, assign a SHORT type data to an INT type variable, and the short value is converted to an INT value and then assigns an INT type variable. Such examples:

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 ("whip 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 passed smoothly, the operation results were values ​​for each variable. Of course, their types are still the system.byte type ... System.double. Now let's try, if the order of assignment is, what is the order? Add a statement in 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): Unable to convert the type "int" implicit to "Short"

Among them, the 118 line of Form1.CS is the line of Short H = G.

At this time, if we insist on the conversion, it should be used to convert, which is often mentioned in the C language, which is to use the "(Type Name) variable name" form in the form of mandatory conversion. As described above, the modification is as follows:

Short g = 1;

BYTE H = (byte) g; // Mandatory for the value of the SHORT type G and then assigns the variable H after the value of the SHORT type G

THIS.TEXTBOX1.APpendText ("h =" h.tostring () "/ n");

Compilation passed, the result of the operation output h = 1, the conversion is successful.

However, if we use forced conversion, you have to consider a problem: SHORT type is -32768 ~ 23767, and the Byte type is 0 ~ 255, then if the size of the variable G exceeds the BYTE type What kind of situation will there be? Let's rewrite the code again, change the value to 265, and 255 big 10

Short g = 265; // 265 = 255 10

BYTE H = (byte) g;

THIS.TEXTBOX1.APpendText ("h =" h.tostring () "/ n");

There is no error in compilation, but the results are not h = 265, but h = 9.

Therefore, when we are converting, it should be noted that the data converted cannot exceed the scope of the target type. This is not only reflected in the multi-byte data type (relative, as the short of the above example) is converted to a small byte type (relative, as the byte of the above), it is also reflected in the same number of symbol types and non-symbol types as the number of bytes. If you convert the 129 of Byte to Sbyte will overflow. The examples in this regard are different, and it will not be described in detail. 3. Character's ASCII code and Unicode code

Many times we need to get an English character ASCII code, or a Unicode code of a Chinese character character, or from the related encoding query which character is encoded. Many people, especially from the VB program to learn C #, will report why C # does not provide ready-made functions to do this - because there is ASC () function and chr () function in VB for this type Conversion.

But if you have learned C, you will clearly, we only need to convert English character data into a suitable numeric data, you can get the corresponding ASCII code; Converse, if a suitable numerical data is forced to convert Character data can get the corresponding characters.

The range of characters in C # expands, not only contains a single-byte character, but also contains double-byte characters, such as Chinese characters. The conversion between characters and encodings still extension of C language practices - 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 = 'in'; 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");

}

Its operation result is

The Ascii Code of 'A' IS: 97

ASCII IS 65, THE CHAR IS: A

The Unicode of '' IS: 20013

Unicode is 22478, The Char is: City

From this example, we can understand that the character's encoding can be encoded, or the encoded characters can be obtained by forced conversion. If you are not Short type encoding, please refer to Article 1 for conversion, you can get the coded value of the INT.

4. Conversion between numerical strings and values

First of all, we have to understand what is a numeric string. We know that in C #, the string is represented by a number of characters contained in a pair of double quotes, such as "123". "123" is relatively special, because the characters that make up the string are numbers, such a string is a numerical string. In our eyes, this is a string of characters, but the computer only thinks it is a string, not a number. Therefore, when we are at some point, when entering a value, we convert a string into a value; at other times, we need the opposite conversion. Converting numeric values ​​into a string very simple because each class has a void toString () method. All numeric Void toString () methods can convert data to a numerical string. Such as 123.TOSTING () will result in a string "123".

So in turn, what should I do if the numeric string is converted into a value? Let's take a closer look, you will find a Static Parse () function. This function is used to convert a string into a corresponding value. We use a float type to convert as an example: float f = float.parse ("543.21"); its result f is 543.21F. Of course, other numerical types can also be converted using the same method, and the following examples can more clearly describe the method of conversion:

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.");

}

}

operation result:

f = 54.321

Str Convert to int surpassfully.

5. Conversion between strings and characters arrays

String class system.string provides a void tocharaRray () method that enables strings to transition to character arrays. Such examples:

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 the case, the results are tested in the length of the character array of conversion to the conversion, and 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, this shows that the conversion is successful. So in turn, how do you want to convert the character array into a string?

We can use the constructor of the System.String class to solve this problem. The System.String class has two constructor constructed by a character number, namely string (char []) and string [char [], int, int). The latter is more than two parameters because it can specify which part of the character array can be constructed. The former is a string with all the elements of the character array. We used to take the following statement as an 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", the test instruction conversion is successful.

In fact, we often need to convert a string into a character array just to get a character in the string. If it is just for this purpose, it can not be able to convert the Master's move, we only need to use System.String [] operator to achieve the purpose. Please see the case, then add the following name in the TestStringChars () function:

CHAR CH = TSTR [3];

THIS.TEXTBOX1.APpendText ("/" TSTR "/" [3] = " ch.toString ());

The correct output is "Test Me" [3] = T, tested, and the output is correct.

6. Conversion between strings and byte arrays

I am afraid you will be disappointed if you want to find the transition between the string and the byte array from the System.String class. In order to make such a conversion, we have to take another class: system.text.encoding. This class provides a BYE [] GetTes (String) method to convert a string into byte arrays, and provide string getString (Byte []) method converts the byte array into a string.

System.Text.Encoding is similar to that there is no useful constructor, but we can find a few default encoding, eNCoding.default (coding of the current ANSI code page of the system), encoding.ascii (get 7 ASCII character set Encoding), encoding.Unicode (get encoding using the Little-Endian byte order), encoding.utf7 (getting encoded UTF-7 format), encoding.utf8 (getting UTF-8 format), etc. Here is the difference between Encoding.default and Encoding.Unicode for conversion.

In the process of string to the byte array, Encoding.default will convert each single-byte character, such as half-width, and convert each double-byte character, such as Chinese characters into 2. One byte. Encoding. Enicode will convert them into two bytes. We can learn about the conversion by following a simple understanding of the way, and using 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 results of the operation are as follows, not to say detailed, I believe everyone has already understood.

B1.LENGTH = 6

67 35 211 239 209 212

B2.LENGTH = 8

67 0 35 0 237 139 0 138

Convert byte arrays into strings, using the String getString (Byte []) or string getString (Byte [], int, int) method using the Encoding class, and what ENCODING is determined by the encoding. Add as an instance of the following statement in the teststringbytes () function:

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 result is: The string is: abcdef

7. Conversion between various numerical types and byte arrays

In Article 1 we can find out how many bytes of spaces need to be used to save data. When a certain type of data is converted into byte array, it is necessary to be a corresponding size byte array; similarly, you need to convert byte arrays into numeric types, and this byte array is required to be greater than the corresponding numerical type. Section number.

The protagonist of such conversion is now introduced: System.bitconverter. This class provides a BYTE [] getBytes (...) method to convert various numeric types into byte arrays, and also provides toint32, toint16, toint64, touint32, tositle, toboolean, etc. to convert byte arrays into corresponding values. Types of. Since such transitions are usually only used when needed to make a thinner encoding / decoding operation, it will not be described in detail here, and only the System.bitConverter class is introduced to everyone.

8. Convert to hex

Any data is stored inside the computer, so that the amount of binding and data is not related to the data of the data is related to the input and output. So, for the credit conversion, we only care about the results in the string.

The TSTRING () method can be converted into a string in paragraph 4, but in the string, the result is displayed in decimal. Now we bring it to add some parameters, you can convert it into hexadecimal - use the toString (String) method.

Here you 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 is mainly in the AF six numbers: "x" represents AF using lowercase letters, and "X" indicates AF Use a large letter letter. Such examples:

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 results of the operation are as follows:

A (10) = 188

A (16) = BC

A (16) = BC

At this time, we may have another demand, that is, in order to display the result, we need to control the length of hexadecimal representation, if the length is not enough, use the leader 0 to fill. To solve this problem, we only need to write a number that represents the length after the format specifier "x" or "x". For example, to limit the length of 4 characters, it can be written as "x4". Add a sentence in the above example:

THIS.TEXTBOX1.APpendText ("A (16) =" a.tostring ("x4") "/ n");

The result will output a (16) = 00bc.

Now, we also have to say how to convert a string that represents a hexadecimal number of strings into integers. This conversion also needs to use the part () method. Here, I need Parse (String, System.globalization.NumberStyles) method. The first parameter is a string representing a hexadecimal number, such as "AB", "20" (indicating a decimal 32). The second parameter system.globalization.NumberStyles is an enumeration type that means that the hexadecimal enumeration value is HexNumber. Therefore, if we want to convert "AB" into an integer, it should be written: int b = int.parse ("ab", system.globalization.numberStyles.HexNumber), the final resulting value is 171.9. Conversion between date data and long integer data

Why convert date-type data to long integer data? There are many reasons, but I personally often use it for date storage of the database. Since various databases are different from date-type definitions and processing, various languages ​​define the definition of date data is different, because I would rather convert the date-type data conversion to the database. Although the string can also be saved, the use of strings will also involve many issues, such as regions and other issues, and it needs to be more space than saving long integer data.

Date data, when participating in C #, it should also be converted to long integer data to operate. Its long integer value is a number that is time-separated by 100 nanoseconds since 12:00 on January 1, 001. This number is called Ticks (scale) in the DateTime in C #. The DateTime type has a long integer read-only attribute called Ticks, saves this value. In this way, it is very simple to get a long type from a DataTime type data, just read the Ticks value of the DataTime object, such as:

Long longdate = datetime.now.ticks;

The DateTime is also provided, a function of constructing DateTime type data from a long integer data: DateTime (long). Such as:

DateTime these = new datetime (longdate);

But so for many VB6 programmers, it has given them a problem, because the date data in VB6 is expressed in Double type, converting it to long integer, only date, and there is no time . How to coordinate these two date types?

System.DateTime provides two functions of Double Tooadate () and Static DateTime FromoAdate (Double) to solve this problem. The former outputs the current object according to the original Double value, which gets a system.datetime object from a Double value. For example, as follows:

Private void testdatetimelong () {

Double Doubledate = datetime.now.tooadate ();

DateTime has 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");}

operation result:

Double Value ofown: 37494.661541713

Datetime from Double Value: 2002-8-26 15:52:37

10. Format Date Data

During programming, it is usually necessary to output the date data according to certain formats. Of course, the output result is definitely a string. To do this, we need to use the TOSTRING () method of the System.DateTime class and specify a format string.

In the MSDN, the mode string has a very detailed description of the mode string in the SYSTEMATINFO class, so I only explain some of the commonly used formats. First, please see the following table:

There is no predecessor of one day in one day in the month.

One day in the DD month is a preamble

The abbreviation name of a day in the DDD week is defined in AbbreviatedDayNames

The full name of the day in the DDDD week is defined in daysNames

Month Number of digital one-month month does not have a preamble zero

MM months have a preamble zero

The abbreviation name of MMM month is defined in AbbreviatedMonthnames

The full name of the MMMM month is defined in Monthnames

Y does not include the year of the era, if the year does not include the year less than 10, the year does not have ahead of the front guide zero

YY does not include the year of the era If the year does not include the year less than 10, the year showing the leading zero

YYYY includes the four-digit year of the era

H 12 hours of hours of hours, one number of hours, no preamble

HH 12 hours a number of hours a number of hours have a preamble zero

H 24 hours a number of hours of one-digit number does not have a predecessor zero

HH 24 hours a number of hours a number of hours has a preamble zero

M minutes, one number of minutes, no preamble

One of the minutes of the MM Minutes One Amissive Zero

S-second one number of seconds no preamble zero

The number of seconds of SS seconds has a preamble zero

In order to facilitate everyone's understanding, try the procedures below:

Private void testdatetiMetString () {

DateTime now = datetime.now;

String format;

THIS.TEXTBOX1.TEXT = "";

Format = "YYYY-MM-DD HH: mm: SS";

THIS.TEXTBOX1.APpendText (Format ":" Now.toTRING (Format) "/ N");

Format = "YY Years M Day D Day";

THIS.TEXTBOX1.APpendText (Format ":" Now.toTRING (Format) "/ N");

}

This program will output results:

YYYY-MM-DD HH: mm: SS: 2002-08-26 17:03:04

YY Years M Day D Day: On the 8th, 26th, 2002

At this time, there is a problem, what should I do if I have a format character in the text information to be output? Such as

Format = "Year: YYYY, MONTH: MM, DAY: DD";

THIS.TEXTBOX1.APpendText (Now.toString (Format) "/ N");

Will output:

2EAR: 2002, 4on 5: 08, 26A2: 26 This is not what I want, what should I do? There is a way--

Format = "/" year / ": YYYY, / 'MONTH /': MM, / 'DAY /': DD";

THIS.TEXTBOX1.APpendText (Now.toString (Format) "/ N");

Look, this time the results are right:

Year: 2002, Month: 08, Day: 26

It can be seen that it only needs to use single quotes or double quotes to enclose text information.

What if the text information contains double quotes or single quotes? This problem, please read the readers!

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

New Post(0)