"Is" vs "AS" in C #

xiaoxiao2021-03-06  56

In data type conversion, C # relatively strictly in other languages, requiring explicit data transformation.

For the convenience of operation, C # also provides an IS operator for conversion, it is very convenient, it automatically checks if the time is compatible, and returns the result. And it won't throw an exception. If the object references null, the IS always returns false.

Class2 CLS2

=

CLS1

AS

Class2;

IF

(CLS2

! =

NULL

) System.console.writeline

"

OK

"

);

Else

System.console.writeline

"

Error!

"

);

Usually you use this way to do the type transformation, but today I read an article, compared another way, the AS operator conversion, only the AS is slightly improved by the AS than IS.

IF

(CLS1

IS

Class2)

{Class2 CLS2 = (Class2) CLS1;}

Else

System.console.writeline

"

Error 2!

"

);

AS is slightly different, it checks if the reference object is compatible, if it is not compatible, return null, so it is necessary to make NULL judgment.

Comparison two ways, IS needs to do two object type checks, and AS needs to do an object type check, add a NULL check, and NULL checks the overhead than the object type. The method of relative AS is higher efficient.

It seems that some habitual code written by the day can always find the improved place, and it is not better to use the new way.

2004-09-16 11:05 Author: Xu before the wind ~

转载请注明原文地址:https://www.9cbs.com/read-116241.html

New Post(0)