C # Learning diary 14 --- object class of reference type
Let's first understand what the object class is.
Object class:
An object class is a base class of all types. All types are derived from it. C # All classes are directly or indirectly derived from Sytem. inheritance in the Object class (it may be a bit confusing. For example, if the Object class is a trunk, all the classes we have learned above are branches or leaves ). Therefore, a variable of the Object type can be assigned a value of any type.
Define an Object variable:
For Object-type variable declaration, the object keyword is used. This keyword is defined in the pre-defined namespace System provided by the. Net Framework Structure and is the alias of the class System. object. The definition format is as follows: object variable name;
Instance:
Using System; using System. collections. generic; using System. linq; using System. text; namespace Test {class Program {static void Main (string [] args) {object Int, Str, Doub, Ch; // defines four object variables Int = 1; // Str = HC666; // string type: Doub = 12.32; // double type: Ch = 'male'; // char type: Console. writeLine (Int = {0} Str = {1} Doub = {2} ch = {3}, Int, Str, Doub, Ch );}}}
Output result: (completely consistent ^_^)
Instance exploration:
The above Object definition emphasizes that the object is a base class of all types. Can we define a Struct class and class to be converted into an object ?? In the above code, I added some elements:
Using System; using System. collections. generic; using System. linq; using System. text; namespace Test {class Program {public struct Student {public string name; public char sex; public uint age;} static void Main (string [] args) {Student stu = new Student {name = HC666, sex = 'mal', age = 19}; // initialize stu object m = stu; // convert stu to object-type object m Student x = (Student) m; // convert object-type m to Student x by force conversion Console. writeLine (name: {0} sex: {1} age: {2}, x. name, x. sex, x. age );}}}
The result is as follows:
The preceding example shows that the Struct and Class types can be converted to the object type. The conversion process is as follows:
Struct ----> object ----> struct; (only Struct ----> Object cannot output values.) The value in stu is not changed during conversion.