This article describes the following:
• Type Conversion
A brief discussion on is/as operator
1. Introduction
Type safety is. NET design at the beginning of the focus on one of the content, for the programmer, the complete grasp of the system data type security, often is the problem of inadequacy. Now, this is all in the Microsoft Daniel's design framework for you to solve. In. NET, all types must be integrated from the System.Object type, so we can easily get the exact type of the object, by: The GetType () method. So. NET type conversion, should be considered where are those?
2. Concept Introduction
Type conversions include display conversions and implicit conversions, and the basic rules for type conversions in. NET are as follows:
- Any type can be safely converted to its base class type, which can be completed by implicit conversion;
- When any type is converted to its derived type, the conversion must be displayed, and the rule of conversion is: (type name) object name;
- The exact type of any object can be obtained using GetType;
- Primitive types can use the covert class to implement type conversions;
- Other than string types have the parse method, which is used to convert the string type to the corresponding base type;
- The conversion mechanism for value types and reference types is called boxing (boxing) and unboxing (unboxing).
3. Principle and Example Description
This paper discusses several aspects of the type conversion, which focus on the IS, as operator's enmity. Type conversion will be a big topic to be discussed at the right time.
The is/as operator, which is used in C # for type conversion, provides a sense of type compatibility, which enables type conversion control in a secure category, providing flexible type conversion control.
The rules for IS are as follows:
- Check the compatibility of the object type and return the result, true or false;
- Does not throw an exception;
- If the object is null, the return value is always false.
The typical usage is:
1 Object o = new Object ();
2
3 Class A
4
5 {
6
7}
8
9 if (O is A)//Perform first type compatibility check
10
11 {
12
A A = (a) O; Perform a second type compatibility check
14
15}
16
17
The rules for as are as follows:
- Checks the compatibility of the object type and returns the result, and returns null if incompatible;
- Does not throw an exception;
- If the result is judged to be null, then forcing the type conversion throws a NullReferenceException exception.
The typical usage is:
1 Object o = new Object ();
2
3 Class B
4
5 {
6
7}
8
9 b b = O as B; Perform a type-compatible check
10
if (b! = null)
12
13 {
14
MessageBox.Show ("B is B ' s instance.");
16
17}
18
19
4. Conclusion
In comparison, the Is/as operator provides a more flexible way to type transformation, but the as operator is more efficient in execution, and we should experience its similarities and differences in actual programming, as appropriate.