The most important feature of CLR is type security. CLR can always know the type of an object at runtime. You can also call the GetType () method to obtain the exact object type. Because this method is a non-virtual method, we cannot use it to tamper with a type of information. (Microsoft. NET Framework Program Design <revision> p117)
We define the following classes:
1: public class Employee
2: {
3: string name= string.Empty;
4: float age = -1;
5:
6: public override string ToString()
7: {
8: return "name = "+name +" and age = "+age;
9: }
10: }
Use the following code:
1: Employee e = new Employee();
2: object oe = e as object;
3:
4: if(oe == null)
5: {
6: Console.WriteLine("oe is null");
7: }
8: Console.WriteLine("oe's type is : {0}",oe.GetType());
The output is as follows:
1: oe's type is : Employee
Through the above, we should be able to understand"CLR can always know the type of an object at runtime..
The as operator provides compatibility tests for instances on the left to the right. If the instances on the Left can be converted to objects of the right type, a reference to the object is returned. Otherwise, null is returned. In addition to the as operator, the is operator is also provided in C #. It also provides a compatibility test between the left-side instance and the right-side instance. However, when the test result is compatible, true is returned, otherwise, false is returned. Therefore, an additional display operation is required to complete the conversion. Therefore, the as operator is more efficient. In addition, no exception is thrown during the two operators. However, the as operator must determine whether to add null references to converted objects to prevent null references when the conversion fails.
Because the as operator returns NULL when the test result is incompatible, The as operator cannot check the instance and value type. Otherwise, the compilation fails. Because the value type cannot be assigned null (? Except ).