/* Author:. Please indicate the source and author when reprinting */
We know that in C #, all types are derived from class objects, and the derived classes and inherited classes can be converted to each other. This introduces the concepts of "Packing" and "unpacking.
Packing: explicitly or implicitly converts a value of a type to the object type, or to an interface inherited by this type. After packing, the value of this object class in the heap area in the memory is a copy of the original type. For example:
Int I = 2;
String STR = "hello ";
Object objstr = STR; // implicit
Object objint = (object) I; // explicitly
Interestingly, you can use obj. tostring () to print the original value after packing. For example, console. writeline (objstr. tostring () displays hello.
Unpacking: explicitly converts the boxed object type to the original type. In this case, the is operator or GetType () can be used to determine the original object type. For example
Int n = (INT) objint;
Int S = (string) objstr;
If (objint is int) console. writeline ("Yeah! ");
If (objstr. GetType (). tostring () = "system. String") console. writeline ("OK ");
Note:
1. If it is not converted to the original type after unpacking, no errors will occur during compilation, but errors will occur during running. Therefore, after unpacking, the conversion type must be correct.
2. When using GetType (). ToString () to judge, use the full name of the type, for example, System. String instead of String.