In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is C# data type conversion". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
There are two ways of type conversion of C #: explicit transformation and implicit transformation.
Explicit transformation: a transformation that has the potential to cause exceptions, loss of accuracy, and other problems. The conversion operation needs to be carried out by means.
Implicit transformation: a transformation that does not change the accuracy of the original data, throws exceptions, and does not cause any problems. Automatically converted by the system.
The operation of different types of data (addition, subtraction, multiplication, division, assignment, etc.) requires type conversion before the operation can continue. So "type conversion" is needed.
Implicit transformation
Implicit transformation is easy to understand. When two or more data types perform certain operations, the system automatically converts implicitly without intervention.
Such as
Int I = 66666bot long b = I; / / assign a value to b after being converted to long type
In general, when multiple value types are calculated, the system automatically undergoes implicit transformation, and always converts to a wider range of data types, and there is no change in accuracy, number size, and so on.
Explicit transformation
The problem is, when you need to convert data of type long to int, or to convert string to int, you have to use explicit transformations when there are too many decimal places.
Before continuing with the following tutorials, I would like to make one point.
Char is an integer!
Although char stores characters rather than numbers, it is an integer, which can be found by looking back at the figure above.
In other words, char can participate in arithmetic operations. But it is not directly involved, but the basic value of char. The char value in c # is based on Unicode. With Unicode, any character can be interpreted as a number.
First, use the ([type]) transformation operator
This method applies to value type conversion (string belongs to the reference type)
Add ([type]) to the variable that needs to be converted
Please observe the difference between the following two pictures carefully.
In the code in the second figure, the second line is int b = (int) I
Use ([type]) this format before the variables that need to be converted, such as (int), (float), (long)
Be careful,
This method can only convert value type data.
You should not convert a wide range of types to a small one or a floating point type to a plastic one. You should not turn an out-of-range type to a small one.
For example, if float is converted to int, the accuracy will be automatically lost.
Output 666
An overflow occurs when a number larger than its type range is given to it.
Char can be used directly with int or long.
Int a ='1' + '3century; / / change from small to big char b = (char) a; / / change from big to small int c =' a' +'5'; / / char can be directly converted to int to note the difference between the above and the above examples. If int is directly converted to char, an error will be reported.
Second, [Type] .Parse ()
([type]) methods cannot be converted between value types and reference types (string types).
But each data type provides a Parse () method that allows strings to be converted to the corresponding numeric type.
Int.Parse ()
Float.Parse ()
Please look at the example
String str = "666"; long I = int.Parse (str); Console.WriteLine ($"{I}, {i.GetType ()}"); Console.ReadKey ()
(pictured)
Be careful,
Parse () is designed to provide functionality for converting string types to value types!
Parse () is a conversion for string types that conform to the numeric format!
The following examples are all misuses!
Parse () converts a string that conforms to the numeric format into a number, that is,
() must be a string in parentheses!
The content of the string must be a number!
Example 1 () the content in parentheses is not a string
Example 2 the content of the variable str is not in a valid numeric format
Third, [Type] .TryParse ()
The format is as follows
Int.TryParse ()
Float.TryParse ()
.TryParse () is similar to .Parse (), but in a different form.
[type] .TryParse (the string to be changed, the variable to which out is stored);
The most important difference is that when the conversion fails, .TryParse () does not throw an exception, but returns flase
Examples
String str = "666"; int i; bool b = int.TryParse (str,out I); / / receive the conversion result or string str = "666"; int I; int.TryParse (str,out I); / / do not receive the conversion result
If you do not know the use of out, please refer to the out parameter / ref parameter / params variable parameter in C#
Fourth, System.Convert
Method example
System.Convert.ToSingle ()
System.Convert.ToInt32 ()
System.Convert.ToDouble ()
System.Convert allows you to change one type to another.
List of common types: char, sbyte, short, int, long, uint, ulong, float, double, decimal, string, bool.
However, format support is also needed!
String str = "666"; int a = System.Convert.ToInt32 (str); / / correct string str = "666.66"; int a = System.Convert.ToInt32 (str); / / error int a = 66666 System.Convert.ToBoolean (a); / / correct string str = "666.66"; bool c = System.Convert.ToBoolean (str); / / error report
System.Convert also needs to pay attention to the format in order to convert successfully.
Similarly, there will be changes in accuracy and digital size in this way.
Fifth, System.Convert
.Tostring ()
Each data type provides a method ToString () that converts to a string type.
Whether it is a value type or various reference types such as DateTime.
ToString () is the easiest to use, please note the red background section of the following example
Using System;using System.IO;public class Test {static void Main () {int a = 666; string aa = a.ToString (); Console.WriteLine ($"{aa}"); float b = 666.666F; string bb = b.ToString (); Console.WriteLine ($"{bb}"); DateTime c = DateTime.Now; string cc = c.ToString () Console.WriteLine ($"{cc}"); FileInfo d = new FileInfo ("E:\\ test.txt"); string dd = d.ToString (); Console.WriteLine ($"{dd}"); string ee; try {int x = 1; int y = 0; int e = x / y } catch (Exception ex) {ee = ex.ToString (); Console.WriteLine ($"{ee}");} Console.ReadKey ();}}
Did you see that? No matter what type, you just need to add ToString () after it, and you can output the content of type string. (not converted to string! )
Of course, ToString () is a method and provides the following parameters, and each type has several overloaded TOString () methods, such as DateTime's
Public string ToString (string format, IFormatProvider provider); public string ToString (string format); public string ToString (IFormatProvider provider); public override string ToString ()
I will not dwell on other aspects.
Copy the following code to the console to see what is output
Using System;using System.IO;public class Test {static void Main () {int a = 666; string aa = a.ToString (); Console.WriteLine ($"{aa}"); float b = 666.666F; string bb = b.ToString (); Console.WriteLine ($"{bb}"); DateTime c = DateTime.Now; string cc = c.ToString () Console.WriteLine ($"{cc}"); FileInfo d = new FileInfo ("E:\\ test.txt"); string dd = d.ToString (); Console.WriteLine ($"{dd}"); string ee; try {int x = 1; int y = 0; int e = x / y } catch (Exception ex) {ee = ex.ToString (); Console.WriteLine ($"{ee}");} Console.ReadKey ();}} "what are the C# data type conversions"? thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.