请告诉我C#中的is和as关键字有什么区别
发布于 2016-11-08 03:11:43
IS和AS都用于安全类型转换
IS Keyword-->检查给定对象的类型是否与新对象类型兼容。它从不抛出异常。这是一个布尔型type..returns,可以为true或false
`student stud = new student(){}
if(stud is student){} // It returns true // let say boys as derived class
if(stud is boys){}// It returns false since stud is not boys type
//this returns true when,
student stud = new boys() // this return true for both if conditions.`AS关键字:检查给定对象的类型是否与新对象类型兼容。如果给定对象与新对象兼容,则返回非null,否则返回null。这会抛出一个异常。
`student stud = new student(){}
// let say boys as derived class
boys boy = stud as boys;//this returns null since we cant convert stud type from base class to derived class
student stud = new boys()
boys boy = stud as boys;// this returns not null since the obj is pointing to derived class`https://stackoverflow.com/questions/3786361
复制相似问题