How do you use convert in C#?
In C#, the Convert class is used to convert one data type to another. The Convert class provides a range of static methods to facilitate conversions between different data types. Here are some commonly used methods of the Convert class:
- Convert.ToBoolean(): Converts the specified object to a boolean value.
- Convert.ToInt32(): converts the specified object to a 32-bit signed integer.
- Convert.ToDouble(): Converts the specified object to a double-precision floating point number.
- Convert.ToString(): converts the specified object into a string.
- Convert.ToDateTime(): Converts the specified object into a date and time.
The instructions for use are as follows:
int intValue = Convert.ToInt32("123"); // 将字符串转换为整数
double doubleValue = Convert.ToDouble("3.14"); // 将字符串转换为双精度浮点数
bool boolValue = Convert.ToBoolean("true"); // 将字符串转换为布尔值
DateTime dateTimeValue = Convert.ToDateTime("2022-01-01"); // 将字符串转换为日期时间
string strValue = Convert.ToString(123); // 将整数转换为字符串
It is important to note that when using the Convert class for type conversion, make sure that the source object’s type is compatible with the target type, otherwise an exception will be thrown.