The difference between strong conversion of brackets in C#, as and is

C# is a strongly typed language. In general, it is best to avoid converting one type to another, but sometimes you have to perform type conversion, so there are several ways to force conversion.

1. Brackets are forced to turn. The conversion check is not performed during the conversion , and the conversion is performed directly. If it fails, an exception will be thrown and the catch statement will be executed. As shown below

2. is. It can be used to judge whether conversion is possible , and the return value of the expression is bool. As shown in the figure below, the result will print that the conversion failed

2. as conversion. Perform a conversion check first in the conversion (equivalent to doing an is operation before a strong conversion) , if it fails, it will return null (so as cannot be used for value types, and value types cannot be null), as shown in the figure below, the result will be printed conversion fail

 

Guess you like

Origin blog.csdn.net/Ling_SevoL_Y/article/details/127774395