In data type conversion, C # is stricter than other languages, and explicit data conversion is required.
For ease of operation, C # also provides an is Operator for conversion, which automatically checks whether the current situation is compatible with the type and returns the result. And it does not throw an exception. If the object reference is null, the is always returns false.
If (Cls1 Is Class2)
{
Class2 cls2=(Class2) cls1;
}
Else
System. Console. writeline ( " Error 2! " );
I usually use this method for type conversion, but today I readArticle, Compared to another method, The as operator is converted to know that as can slightly improve the performance than is.
Class2 cls2 = Cls1 As Class2;
If (Cls2 ! = Null )
System. Console. writeline ( " OK " );
Else
System. Console. writeline ( " Error! " );
As is slightly different. It checks whether the referenced object is compatible. If it is not compatible, null is returned. Therefore, null is required.
Comparing the two methods, is requires two object type checks, while as requires an object type check and a null check. The null check overhead is less than the object type check. It is more efficient than the as method.
It seems that some of the daily writing habitsCodeWe can always find improvements. Isn't it better to use new methods as a habit?
The as operator is used to explicitly convert a value to a specified reference type through reference conversion or packing conversion. Unlike Explicit conversions, as does not produce any exceptions. If the conversion fails, the result value is null. E is an expression and T is a reference type. The type of the returned value is always T type, and the result is always a value.
For example, when youProgramWrite the following statement:
String S = 'A' as string
Although the character type cannot be converted to the string type, the program can still be compiled, but there is a warning:
The given expression is never of the provided ('string') type.