1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace TypeCast
7{
8 internal class Employee
9 {
10
11 }
12 internal class Manager : Employee
13 {
14
15 }
16 class Program
17 {
18 static void Main(string[] args)
19 {
20 Manager m = new Manager();
21 Employee e = m as Employee;
22 if (e != null)
23 {
24 Console.WriteLine(e.GetType().ToString());
25 }
26
27 PromoteEmployee(m);
28 //the cast above no fails:Cause Manager is derived from Employee
29
30
31 Object o = new object();
32 Employee e1 = o as Employee;
33 if (e1 != null)
34 {
35 Console.WriteLine(e.GetType().ToString());
36 }
37 //the cast above fails:no exception is thrown,but e1 is set to null
38
39 PromoteEmployee(o);
40 //the cast above fails: exception is thrown
41 }
42
43 public static void PromoteEmployee(Object o)
44 {
45 Employee e = (Employee)o;
46 Console.WriteLine(e.GetType().ToString());
47 }
48 }
49
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5
6namespace TypeCast
7{
8 internal class Employee
9 {
10
11 }
12 internal class Manager : Employee
13 {
14
15 }
16 class Program
17 {
18 static void Main(string[] args)
19 {
20 Manager m = new Manager();
21 Employee e = m as Employee;
22 if (e != null)
23 {
24 Console.WriteLine(e.GetType().ToString());
25 }
26
27 PromoteEmployee(m);
28 //the cast above no fails:Cause Manager is derived from Employee
29
30
31 Object o = new object();
32 Employee e1 = o as Employee;
33 if (e1 != null)
34 {
35 Console.WriteLine(e.GetType().ToString());
36 }
37 //the cast above fails:no exception is thrown,but e1 is set to null
38
39 PromoteEmployee(o);
40 //the cast above fails: exception is thrown
41 }
42
43 public static void PromoteEmployee(Object o)
44 {
45 Employee e = (Employee)o;
46 Console.WriteLine(e.GetType().ToString());
47 }
48 }
49
注意:用As 类型转换操作不会抛出异常.