Due to the deep-rooted nature of Delphi, the information about "is" and "as" has always been omitted. I always thought it was the same as in Delphi, because in. net is much the same as Delphi.
I read the. NET Framework until yesterday.ProgramDesign found that there was a difference between the two. This difference directly led to some suggestions on type conversion between. NET and Delphi.
Under Delhi (CodeNo Delphi at hand ),
Type
A = Class (tobject );
B = Class ();
VaR
Insta:;
Instb: B;
Begin
Insta: = B. Create;
If (insta is B) then
Instb: = insta as B;
End;
The "Delphi * developer Guide" and many materials all describe this method. Because "as" requires rtti information and affects performance, most of them will provide the following method:
If (insta is B) then
Instb: = B (insta );
After the conversion is determined, the pointer is used for type conversion.
I read the book yesterday and found it under. net. "is" is still the "is", but "as" is no longer the ". Here, "as" does not throw an exception. If the conversion fails, it only produces a null value.
If the book is not around, post an SDK document:
TheAsOperator is like a cast failed t that it yields null on conversion failure instead of raising an exception. More formally, an expression of the form:
Expression as type
Is equivalent:
Expression is type? (Type) expression: (type) null
Else t thatExpression
Is evaluated only once
That is to say, "as" is actually integrated with "is" and type cast.
Note the last sentenceElse t thatExpression
Is evaluated only onceThat is to say, although the effect is equivalent, it is better to use "as" in terms of efficiency.
Verified:
Using System;
Namespace Typecast
{
/**/ /// <Summary>
///Summary Description for class1.
/// </Summary>
Class Class1
{
/**/ /// <Summary>
///The main entry point for the application.
/// </Summary>
[Stathread]
Static Void Main ( String [] ARGs)
{
Const Int Testcount = 500000000 ;
Long TT;
A = New B ();
B;
TT = Datetime. Now. ticks;
For ( Int I = 0 ; I < Testcount; I ++ ) {
If ( Is B) {
B=(B);
B. x= 1;
}
}
TT = Datetime. Now. ticks - TT;
Console. writeline ( " Test 'is 'operator: {0} " , TT. tostring ());
TT = Datetime. Now. ticks;
For ( Int I = 0 ; I < Testcount; I ++ ) {
B = A As B;
If (B ! = Null ) {
B. x= 1;
}
}
TT = Datetime. Now. ticks - TT;
Console. writeline ( " Test 'as' OPERATOR: {0} " , TT. tostring ());
Console. Read ();
}
Class A {
}
Class B: {
Public IntX;
}
}
}
Result:
Test 'is' OPERATOR: 115460267
Test 'as' OPERATOR: 68695354
It is indeed much faster, almost doubled.
It seems that there are still good documents,
The. NET Framework programming book is really good.