Is and as are common operations in. net. Both of them can implement type-safe conversion, but they are different.
For example
Public class employee {} public void add (Object OBJ) // write method 1 {employee e = NULL; If (obj is employee) {e = (employee) OBJ; // normal processing} else {// other processing} public void add (Object OBJ) // write method 2 {employee e = OBJ as employee; If (OBJ = NULL) {// other processing} else {// normal processing }}
In the above Code, obj is converted to employee, both of which are OK in writing and can be compiled and run. However, the two have some differences in performance.
The is operation needs to determine whether the OBJ type is employee. If yes, it will be forcibly converted to E = (employee) obj. During forced conversion, CLR will judge the type of OBJ again. If it is not of the employee type,
System. invalidcastexception is thrown.
The as operator performs a type judgment in the CLR stage. If it is an employee, it is converted to the employee type. If not, it is converted to null. Therefore, we can determine if (OBJ = NULL) in the second method.
I believe that I have understood the performance differences between the two methods. The expression of IS requires two type judgments, and as only requires one type judgment.
Of course, some programmers directly adopt the following method:
Public void add (Object OBJ) // write method 3 {try {employee e = (employee) OBJ; // normal processing} catch {// other processing throw ;}}
Statement 3 is feasible in the program, but it is not recommended to use try-catch to catch exceptions that fail to force conversion, which has a greater impact on performance.
The fourth edition of CLR via C # is more inclined to write 2.