为了避免在进行强制类型转换时由于目标类型无效,而导致运行时抛出InvalidCastException异常,C#提供了IS与AS操作符进行类型判断与“安全”的强制类型转换。
代码如下:
1 class Program {
2
3 static void Main(string[] args)
4 {
5 Object studentObj = new Student();
6
7 Object studentProgram = new Program();
8
9 //使用IS去检测studentObj引用的对象是否兼容于Student类型
10 //IS永远不会发生异常,当studentObj变量的引用为null时则永远返回false;
11 if (studentObj is Student)
12 {
13 Student studentTemp = (Student)studentObj;
14
15 }
16 if (studentProgram is Student)
17 {
18 Console.WriteLine(studentProgram.ToString());
19 }
20
21 }
22 }
2
3 static void Main(string[] args)
4 {
5 Object studentObj = new Student();
6
7 Object studentProgram = new Program();
8
9 //使用IS去检测studentObj引用的对象是否兼容于Student类型
10 //IS永远不会发生异常,当studentObj变量的引用为null时则永远返回false;
11 if (studentObj is Student)
12 {
13 Student studentTemp = (Student)studentObj;
14
15 }
16 if (studentProgram is Student)
17 {
18 Console.WriteLine(studentProgram.ToString());
19 }
20
21 }
22 }
由代码可以看出,CLR实际会检查两次对象的类型,IS操作符首先检测变量的引用是否兼容于指定的类型,如果返回TRUE,则CLR在进行强制类型转换行进行第二次类型的检测,即studentObj对象是否引用一个Student类型。
由于强制类型转换CLR必须首先判断变更引用对象的实际类型,然后CLR必须去遍历继承层次结构,用变量引用类型的每个基类型去核对目标类型。这肯定会对性能造成一定的影响。好在C#提供了AS操作符来弥补这一缺陷。
代码如下:
1 class Program {
2
3 static void Main(string[] args)
4 {
5 Object studentObj = new Student();
6
7 Object studentProgram = new Program();
8
9 //CLR检测studentObj引用对象类型兼容于Student,as将直接返回同一个对象的一个非null引用
10 //即studentObj保存的对在托管堆上Student对象的引用
11 Student s1 = studentObj as Student;
12 //如果CLR检测studentProgram引用对象类型不兼容目标类型,即不能进行强制类型转换,则返回一个null,永远不会抛出异常
13 Student s2 = studentProgram as Student;
14
15 if (s1 != null)
16 {
17 s1.Work();
18 }
19
20 if (s2 != null)
21 {
22 s2.Work();
23 }
24 }
25 }
2
3 static void Main(string[] args)
4 {
5 Object studentObj = new Student();
6
7 Object studentProgram = new Program();
8
9 //CLR检测studentObj引用对象类型兼容于Student,as将直接返回同一个对象的一个非null引用
10 //即studentObj保存的对在托管堆上Student对象的引用
11 Student s1 = studentObj as Student;
12 //如果CLR检测studentProgram引用对象类型不兼容目标类型,即不能进行强制类型转换,则返回一个null,永远不会抛出异常
13 Student s2 = studentProgram as Student;
14
15 if (s1 != null)
16 {
17 s1.Work();
18 }
19
20 if (s2 != null)
21 {
22 s2.Work();
23 }
24 }
25 }
由此可以看出,在对s1 s2变量进行应用时,还需要进行非null的判断,从而避免出面NullReferenceException的异常。
显然无论从性能还是代码的的直观上来说,AS都IS更胜一筹,然而实际应用中,还是根据环境再做取决了。