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