Home > Backend Development > C#.Net Tutorial > C# difficulties solved one by one (9): type conversion

C# difficulties solved one by one (9): type conversion

黄舟
Release: 2016-12-22 14:26:28
Original
1367 people have browsed it

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;
Copy after login

Explicit conversion can also be performed;

/*显式转换*/ 
int intNum = 23; 
long longNum2 = (long)intNum;
Copy after login

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);
Copy after login

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);
Copy after login

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("转换失败"); 
}
Copy after login

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());
Copy after login

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 (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template