C # provides a "unified type system ". All types, including value types, are inherited from the object type.
You can call methods of the object class on any variable, or even include basic types such as int.
Example:
1 using System;
2 class Test
3 {
4 static void Main (){
5 Console. WriteLine (3. ToString ());
6}
7}
An integer constant calls the ToString method defined by the object class, and the output is "3 ".
Example:
1 class Test
2 {
3 static void Main (){
4 int I = 123;
5 object o = I; // boxed
6 int j = (int) o; // unpack
7}
8}
Very interesting.
An int value can be converted into an object and then converted back.
This example uses packing and unpacking.
When a value type variable is converted to a reference type, an object box is allocated to store this value. Unpacking is the opposite process.
When an object box is converted back to its original value type, the value will be copied from the box and uploaded to the corresponding storage location.
The uniformity of this type gives the value type the benefit of the reference type while eliminating unnecessary expenses.
For programs that do not need to use the value type as the object type, the int type is only a 32-bit value.
This feature can use the value type as the object type, eliminating the difference between the value type and the reference type. This difference exists in most other languages.
For example, a Stack class includes the Push and Popular methods, which respectively include an object-type parameter and an object value:
1 public class Stack
2 {
3 public object Pop (){...}
4 public void Push (object o ){...}
5}
Because C # has a unified type system, this Stack class can be used for any type, including value types such as int.