Chapter 1 C # is and,
I. clarify two basic concepts
Implicit conversion:
A. For value types, low precision => high precision. Eg: int => long
B. For reference types, the process of converting child classes to ancestor classes. Eg: Object => Object
Explicit conversion: displays the inverse process of implicit conversion.
For c #, other terms related to type conversion are not mentioned here, for example:
- Unpacking and packing
- GetType: Get Object type (System. Object. ReferenceEquals (Object obj1, Object obj2 ))
- Basic Type: Convert class;
- Parse ();
- ToString ();
Ii. Why use is and
To avoid system crash caused by conversion failure, we usually use try ...... catch ..... finally .... to avoid program crashes and other problems. Of course, this is also convenient for testing. This is one of the functions of is and as. In addition, try .... catch .... as far as possible, is and as meet this principle.
Iii. Example
1. is usage
Definition: determines whether an object is compatible with another object. Never throw an exception.
Return Value: Boolean value. If compatible, true is returned. If incompatible, false is returned. If the object is null, false is returned;
Example 1: compatible with Label lbl = new Label (); if (lbl is Object) {Object objLbl = (Object) lbl; Response. write ("true");} else {Response. write ("false ");}
Test result: true
Example 2: incompatible Label lbl = new Label (); if (lbl is TextBox) {Response. write ("true");} else {Response. write ("false");} Test Result: false
Example 3: The Object is NULLLabel lbl = null; if (lbl is Object) {Response. Write ("true") ;}else {Response. Write ("false ");}
Test result: false
Is General structure:
If (A is B) // The First compatibility check {B B = (B) A; // The second compatibility check}
Analysis: For is, CLR checks the compatibility twice. The first checks whether A is B. If it is true, it checks B B B = (B) A again;
2. as usage
Definition: determines whether an object is compatible with another object. Never throw an exception.
Return Value: If compatible, return results. If not compatible, return null. If null, return null.
Example 1: compatible
Label lbl1 = new Label (); Label lbl2 = lbl1 as Label; Response. Write (lbl2); // System. Web. UI. WebControls. Label
Example 2: incompatible
String str = "AS conversion"; Label lbl = str as Label; // display the compilation error Response. Write (lbl );
Example 3: The Object is Null Object obj = null; Label lbl = obj as Label; Response. Write (lbl); // null
Iv. Comparison
Since CLR checks is twice and performs as only once, as is more efficient. Generally, as is not used.
Reference: http://developer.51cto.com/art/200908/145432.htm;http://developer.51cto.com/art/200908/145432.htm