I. type conversion
1. Any type can be converted to its base class type, which is completed by implicit conversion;
2. Display conversion is required when any type is converted to its derived type. For example: (type name) Object Name;
3. Use GetType to obtain the exact type of any object;
4. You can use the convert class to convert basic types;
5. All types except string have the parse method, which is used to convert the string type to the corresponding basic type;
6. The conversion between the value type and the reference type is called boxing or unboxing );
2. is/as Example
Is conversion rules:
1. Check the compatibility of object types and return true (false );
2. No exception is thrown;
3. If the object is null, false is returned;
Example:
C # Code
-
- ObjectO ="ABC";
-
- If(OIs String)// Perform the first type compatibility check
- {
-
- StringS = (String) O;// Perform the second type compatibility check and convert
-
- MessageBox. Show ("Conversion successful! ");
-
- }
-
- Else
-
- {
-
- MessageBox. Show ("Conversion failed! ");
-
- }
Object o = "ABC"; if (O is string) // perform the first type compatibility check {string S = (string) O; // perform the second type compatibility check, and convert MessageBox. show ("conversion successful! ");} Else {MessageBox. Show (" Conversion failed! ");}
As conversion rules:
1. Check the compatibility of object types and return the conversion result. If not, null is returned;
2. No exception is thrown;
3. If the result is null, an nullreferenceexception exception will be thrown during forced type conversion;
Example:
C # code
- Object O = "ABC" ;
- string S = O as string ; // executes the first type compatibility check and returns the result.
- If (s! = null )
- MessageBox. Show ( "conversion successful! " );
- else
- MessageBox. Show ( "Conversion failed! " );
Object o = "ABC"; string S = O as string; // execute the first type compatibility check and return the result if (s! = NULL) MessageBox. Show ("conversion successful! "); Else MessageBox. Show (" Conversion failed! ");
Note: As performs a compatibility check less than is, and the performance may be slightly higher.