Msdn:
Http://msdn2.microsoft.com/zh-cn/library/scekt9xw (VS.80). aspx
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. However, I read an article today and compared it with another method. The as operator is used for conversion, 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.