Analyze problems
Programmers often face some type conversion tasks, some of which are deterministic and convertible. For example, a type object is converted into a base class object, while some are tentative, for example, if you want to convert an object referenced by a base class to a subclass, the programmer should be prepared to catch exceptions when such an attempt is executed.
When an incorrect type is converted into a row, an invalidcastexception occurs. Programmers sometimes use try and catch blocks to perform some tentative type conversion. Such code has no errors, however, the performance is quite poor. An exception is a resource-consuming mechanism. When an exception is thrown, the exception stack will be created and the exception information will be loaded. These work costs are usually relatively high, in addition, this information is meaningless during the trial conversion. Therefore, C # provides another syntax for trial type conversion, that is, the work done by the keyword is and.
The is statement is used to determine whether an object can be converted to another object. If yes, true is returned. If no, false is returned. The as statement implements a similar function. It checks the object for trial. If it can be converted to a specified object, the converted reference is returned. If not, null is returned.
Answer
Using the is and as statements instead of forced conversion can effectively avoid invalidcastexcepiton exceptions, and the execution efficiency is relatively high. The reader should use the is or as statement instead of the direct use of forced conversion.