The Convert class
The Convert class uses the following conversion methods:
methods | instructions |
---|---|
Convert.ToInt32() | Convert to an int |
Convert.ToChar() | Convert to char |
Convert.ToString() | Convert to a string |
Convert.ToDateTime() | Convert to datetime |
Convert.ToDouble() | Convert to a double |
Conert.ToSingle() | Convert to single-precision float |
1. If the types of two variables are compatible, automatic casting or cast can be used
2. If the two variables are incompatible, we use the Convert factory of Convert for the conversion
Use cases:
try
{
intValue = Convert.ToInt32(rule.Value);
}
catch (Exception e) // If int fails, it is considered bool
{
try
{
boolValue = Convert.ToBoolean(rule.Value);
}
catch (Exception ex)
{
isBool = false; }}Copy the code
C# Convert vs. Parse
The following content is taken from Baidu Q&A: the original link
1) For conversion objects, convert.toint32 () can be of multiple types (e.g., bool, DateTime, etc.), int.tryparse () and int.parse () can only be integer string types (i.e., the form after each integer ToString(), Int.TryParse() also returns false, with an output argument of 0). (int) can only be numeric (e.g. Float,int,uint, etc.).
2) For NULL values, both the (int) cast and int.parse () cannot accept NULL from a runtime error standpoint; Convert.toint32 () does a check before converting, if NULL, return 0, otherwise int.Parse() is called, int.TryParse() does an exception on int.Parse(). Return false if an exception occurs and return the output argument to 0; 3) For floating-point trade-offs, only convert.toint32 () and (int) can be converted, but trade-offs are also made. The trade-offs taken by convert.toint32 () are rounded, while (int) intercepts the integer part of the floating-point, ignoring the decimal part. For example, convert.toint32 (1.499d) and (int)1.499d both return 1, convert.toint32 (1.5d) returns 2, and (int)1.5d still returns 1;
4) Regarding overflow, convert.toint32 () and int.parse () both report an overflow error when converting a large data type to a small one. The value is too large or too small for Int32, while (int) does not report an error, but returns -1.
Parse() if it is an integer string, and convert.toint32 () if it is not one of these two types.