Forced type conversions in C #
For example, there are two classes of ClassA and CLASSB
Create an object of two classes to convert
| 12 |
ClassA a = newClassA(); ClassB b = newClassB(); |
If you use the cast
Report InvalidCastException exception cannot cast an object of type ClassA to a type CLASSB
If you use the AS keyword for conversion
| 12345 |
ClassB c=a asClassB; if(c!=null) { MessageBox.Show(c.ToString()); } |
If a and CLASSB are incompatible, then NULL is returned to C
In C #, we can see three types of forced-type conversions, such as casting to signed 32-bit integers, and you can find the following three ways:
① (int) () ②convert.toint32 () ③int. Parse ()
Three kinds of transformations can be common in some data, but there is still a big difference in usage.
(int) is a type conversion that uses an explicit cast. Implicit conversions can be used when we type from int to long, float, double, or decimal, but when we convert from a long type to an int type we need to use an explicit cast, otherwise a compilation error is generated.
Convert.ToInt32 () Converts the value of multiple types (including object reference types) to the int type because it has many overloaded versions [2]:
public static int ToInt32 (object);
public static int ToInt32 (BOOL);
public static int ToInt32 (byte);
public static int ToInt32 (char);
public static int ToInt32 (decimal);
public static int ToInt32 (double);
public static int ToInt32 (short);
public static int ToInt32 (long);
public static int ToInt32 (sbyte);
public static int ToInt32 (string);
Int32.Parse () converts a string containing a number to a 32-bit signed integer, which belongs to the content conversion
We have a common method: public static int Parse (string).
If the string is empty, the ArgumentNullException exception is thrown;
Throws an FormatException exception if the string format is incorrect;
If the value of string is less than MinValue or a number greater than MaxValue, the OverflowException exception is thrown.
As can be seen, the function ofConvert.ToInt32 () is the most powerful, it put int32.parse () function includes, also say is int32.parse () is A special case of Convert.ToInt32 ().
The difference between forced type conversions and as conversions in C #