Type conversion in C # .NET

xiaoxiao2021-03-06  117

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 introduced int-> int32 is a packing process, and vice versa is the process of unbo 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? It is common to have some of the following: BOOL -> System.Boolean (Boolean, its value is true or false) char -> system.char (character type, occupying two bytes, represents 1 Unicode character) Byte -> System. BYTE (byte, 1 byte, representing 8 positive integers, range 0 ~ 255) sbyte -> system.sbyte (with symbolic byte type, 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 bits Positive integersion, range 0 ~ 4, 294, 967, 295) Ulong -> system.uint64 (no sign long, accounting for 8 bytes, representing 64-bit positive integers, ranging from 0 to about 10) SHORT -> System.Int16 (Short Integer, accounting for 2 bytes, representing 16-bit integers, 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 - (10 19) times to 10 of 19) FLOAT -> System.single (single precision floating point, 4 words Day) 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, type is System. Windows.Forms.TextBox // Design has been set 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 = ""; th Is.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 "} New button in the form and call this Testalias () in its click event Function, we will see the results as follows: byte -> system.byte char -> system.char short -> system.int16 int-> system.int32 long -> system.int64 uint -> system.uint32 bool -> system.uint32 .Boolean is enough to explain each other class! 2. Mutual conversion between numerical types This value includes byte, short, int, long, fload, double, etc., according to this order, various types of values ​​can be automatically converted backwards. 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 ("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");} Translation passed, the result is The values ​​of each variable are 1; of course, their types are still SYSTEM.BYTE types ... System.double.

Now let's try, if the order of assignment is, what is the order? Add the following statement in the TestBasic () function: int g = 1; short h = g; this.TextBox1.AppendText ("h =" h.tostring () "/ n"); result compile error: g: / Projects / Visual C # / Convert / Form1.cs (118): Unable to convert the type "int" implicit to "Short" where Form1.cs 118 lines are 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 following example 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 this.textBox1.AppendText ("h =" h .Tostring () "/ n"); Compilation pass, run the result 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, more than 255 large 10 short g = 265; // 265 = 255 10 byte h = (byte) g; this.TextBox1.appendtext ("h =" h. ToString () "/ n"); there is no error, but the result is 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 for a Chinese character, or query it from the associated encoding. 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 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 uncode of / '" cn " /' is: " (short) CN " / n "); THIS.TEXTBOX1.APpendText ("Unicode Is" uc.tostring () ", The char is:" (char) uc "/ n");} It 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 very clear - through forced conversion, you can get characters Coding or get the character encoded. If you are not Short type encoding, please refer to Article 1 for conversion, you can get the coded value of the INT. 4. The conversion between numerical strings and values ​​first, 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 be more clearly explained: 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 successful. ");} else {this.textBox1.AppendText (" Str Convert to int failed. ");}} Run results: f = 54.321 Str Convert to int successful. 5. Strings and character arrays Conversion 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");} example in the case of the character array length of the conversion and its elements, the results are as follows: Length of "mytest" IS 6 Length of char Array IS 6 char [2] = t 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.

For the former, we have an example. Enter the following statement in the TestStringChars () function: char [] tcs = {'t', 'e', ​​'s', 't', '', 'm', 'e'}; String tstr = new string (tcs); this.textBox1.AppendText ("TSTR = /" " TSTR " / "/ n"); running results Enter TSTR = "Test Me", the test instructions are 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 following example, then add the name as follows: 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. Transformation between strings and byte arrays If you still want to find a string and byte arrays from the System.String class, I am afraid you will be disappointed. 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 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.uitode.getbytes (s); string t1 = ", t2 ="; forward (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 result is as follows, not to say detailed, I believe that 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 of the Encoding class (byte []) or string getString (Byte [ ], Int, int) method, what kind of eNCoding is determined by coding. Add 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"); Run results: the string is: abcdef 7. Various numerical types and byte arrays In Article 1 we can find Various numerical types require how many bytes of space 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 credit and data is not 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 operation results are as follows: a (10) = 188 a (16) = BC A (16) = BC This time, we may have another demand, that is, to display the neatness of the results, we need Control the length of hexadecimal representation, if the length is not enough, use the leading 0 to fill it. 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 integers, it should be written: int b = int.parse ("ab", system.globalization.numberStyles.HexNumber), the final result is 171.

9. Why is the conversion between date data and long integer data to 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 value from a DataTime type data, just read the Ticks value of the DataTime object, such as: long longdate = datetime.now.ticks; DateTime's constructor also provides the corresponding Structure of DateTime type data from long integer data: DateTime (long). Such as: datetime has = new datetime (longdate); But this is a problem for many VB6 programmers, because the date data in VB6 is expressed in Double type, converting it to long finish The type is only the 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 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 () "});} Run Result: Double Value Of now: 37494.661541713 DateTime from Double Value: 2002-8-26 15:52:37 10. In the process of formatting date data, the date data is usually required to be output according to certain formats. Of course, the output 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: One day in the month Date There is no preamble zero DD monthly one-digit date having a leader zero DDD week an abbreviation name Defines the full name of DDDDDAYNAMES in DayNames Define M Month Number One There is no preamble zero MM month digital one-digit month with a leader zero MMM unpackold name in AbbreviatedMonthnames, defines the full name of MMMM month in MonthNames. Y does not contain the year, if it does not contain the year, less than 10, Then, the year does not contain a leading zero, YY does not include the year, if the year does not contain the year less than 10, then the year of the year, YYYY YYY, including the era, including the four-digit year, Her time, one-digit hour No preamble zero HH 12 hours a bit number of hidden hours with a preamble zero HH 24 hours a bit number without preamble zero hh 24 hours a bit number of hours a bit number preamble zero M The number of minutes in minutes without the maximum number of minutes of the zero MM minute, one number of seconds. There is no preamble zero SS second one number of seconds number of seconds, there is a leader to facilitate everyone's understanding , Try the procedure below: private void testdatetimetostring () {datetime now = datetime.now; string format; this.textBox1.text = ""; format = "YYYY-MM-DD HH: mm: ss"; TextBox1.AppendText (Format ":" Now.toTRING (Format) "/ n"); Format = "YY Years M-day D Day"; this.TextBox1.AppendText (Format ":" Now.toString Format) "/ n");} This program will output the result: YYYY-MM-DD HH: MM: SS: 20 02-08-26 17:03:04 YY Years D Japanese: At this time on the 8th, on the 26th, there is a problem, what should I do if the format character is included in the text information to be output? Such.TextBox1.AppendText (now.tostring (format) "/ n"); 3: 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 run results are: Year: 2002, Month: 08, day: 26 It can be seen that only the single quotes or double quotes will enclose text information.

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

New Post(0)