c# basic grammar の is and as



1. Type conversion

Any type can be converted to its base type, completed by implicit conversion.
Any object can be converted to its derived class, but the conversion must be displayed, such as (type) object name.
Use GetType to get the exact type of any object. The
base type can be converted by Convert Perform display conversion
In addition to string, other types have parse methods, which are used to convert string types into corresponding basic types. For example: double.Parse(string) is equivalent to Convert.ToDouble(string)
The conversion between value types and reference types is called boxing and unboxing


2. is and as

is: Check whether it is compatible with the given type and does not perform the actual conversion. If it is judged that the type reference is null, it returns false. Since it only judges whether it is compatible, no exception will be thrown. The scope of use is only applicable to reference type conversion, boxing conversion and unboxing conversion, and does not support value type conversion.

as: Used to convert between two application types. If the conversion fails, it returns null without throwing an exception. Therefore, whether the conversion is successful can be judged by the result being null, and it can only be judged at runtime. The AS operator has a certain scope of application, it is only applicable to reference types or types that can be null.

The is operator is to determine whether the as operator can be converted
for type conversion


Reasons for using the AS operator as much as possible in actual work:

Whether it is the as or is operator, it is safer than directly using () and direct strong type conversion. It
will not throw exceptions, and avoid the use of try...catch for exception capture and system overhead. You only need to determine whether it is null.
Using AS is better than IS Good (the c#4.0 authoritative guide says so)

Guess you like

Origin blog.csdn.net/zhaozhao236/article/details/112557455