I. Basic Types
1. type conversion:
A derived class is converted to a base class without forced conversion. The base class must be forcibly converted to a derived class.
Object o = new employee ();
Employee E = (employee) O;
Non-Derived classes. CLR prohibits conversion and throws system. invalidcastexception.
2. Is and as operator Transformation
Similarities:
Is and as check whether an object is compatible with the specified type.
Never throw an exception
Differences
Is returns true or false
As returns a non-null reference to the same object. If not compatible, null is returned.
Object o = new object ();
Bool b1 = (O is object); // B1 is true.
Bool b2 = (O is employee); // B1 is false.
If (O is employee ){
Employee E = (employee) O;
// Use e in the remaining part of the IF statement
}
InCodeFor the first time, check whether o is compatible with the employee type. In the if statement, CLR checks again whether o references an employee.
The as operator simplifies the code and improves performance.
Employee E = O as employee;
If (E! = NULL ){
// Use e in the IF statement
// If the object cannot be transformed, the result is null. If you attempt to directly use the final reference, the system. nullreferenceexception will be thrown.
}
Object o = new object ();
Employee E = O as employee; // The Transformation Operation will fail without throwing an exception. The value of E is set to null.
E. tostring (); // throw system. nullreferenceexception