Home >Backend Development >C#.Net Tutorial >C# difficulties solved one by one (9): type conversion
Explicit conversion and implicit conversion
Conversion between types can be divided into implicit conversion and explicit conversion. For example, the int type can be directly converted to the long type.
/*隐式转换*/ int intNum = 23; long longNum1 = intNum;
Explicit conversion can also be performed;
/*显式转换*/ int intNum = 23; long longNum2 = (long)intNum;
Parse
Each value type contains Parse() according to the law, which converts the string into the corresponding numerical type]
/*Parse转换*/ string text = "3.1415926E1"; float PI = float.Parse(text);
Convert
System.Convert belongs to .net The class in the framework is a non-inheritable class. Its prototype is defined in msdn as
public sealed class ConvertSystem.Convert only supports a predefined number of types. The types it supports include all value types plus the basic data types of the String type and the Object type. , the basic data type here is the data type of .net framework.
/*Convert转换*/ bool isTrue=false; string strNum = Convert.ToString(isTrue);
TryParse()
TryParse is a C# static method, and all basic data types include this method. It returns a bool type, indicating whether the conversion is successful. It is often used with out to convert data; if the conversion fails, it will return false and will not throw an exception.
/*TryParse转换*/ System.Console.Write("输入要转换的数值:"); string input = System.Console.ReadLine();//输入 int result;//转换结果 if (int.TryParse(input, out result)) { System.Console.WriteLine("转换结果为:{0}", result); } else { System.Console.WriteLine("转换失败"); }
ToString()
All types support the ToString() method. Only when the type explicitly implements ToString() will the string representation of the value of the object of this type be returned; for other types, ToString() only Returns the name of the data type.
Object o = new object(); Console.WriteLine(o.ToString()); int age = 23; Console.WriteLine(age.ToString()); bool isMale = true; Console.WriteLine(isMale.ToString());
The above is the content of C# difficulties one by one (9): type conversion. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!