关键点
-
is 运算符用于检查对象的运行时类型是否与给定类型兼容,而 as 运算符用于在兼容的引用类型或 Nullable 类型之间执行转换.
-
如果给定对象的类型相同,is 运算符返回 true,而 as 运算符在与给定类型兼容时返回对象.
-
如果给定对象不是同一类型,is 运算符返回 false,而 as 运算符在无法转换时返回 null.
-
is 运算符仅用于引用、装箱和拆箱转换,而 as 运算符仅用于可空、引用和装箱转换.
-
is 运算符关键字仅考虑引用、装箱和拆箱转换
-
is 运算符不考虑用户定义的转换或使用隐式和显式定义的转换。 对于在编译时已知或由隐式运算符处理的转换,is 运算符将为此发出警告
-
as 运算符关键字仅用于可空、引用和装箱转换。 它不能执行只能通过使用强制转换表达式执行的用户定义的转换。
样例
- is operator:
// C# program to illustrate the
// use of is operator keyword
using System;
// taking a class
public class P { }
// taking a class
// derived from P
public class P1 : P { }
// taking a class
public class P2 { }
// Driver Class
public class GFG {
// Main Method
public static void Main()
{
// creating an instance
// of class P
P o1 = new P();
// creating an instance
// of class P1
P1 o2 = new P1();
// checking whether 'o1'
// is of type 'P'
Console.WriteLine(o1 is P);
// checking whether 'o1' is
// of type Object class
// (Base class for all classes)
Console.WriteLine(o1 is Object);
// checking whether 'o2'
// is of type 'P1'
Console.WriteLine(o2 is P1);
// checking whether 'o2' is
// of type Object class
// (Base class for all classes)
Console.WriteLine(o2 is Object);
// checking whether 'o2'
// is of type 'P'
// it will return true as P1
// is derived from P
Console.WriteLine(o2 is P1);
// checking whether o1
// is of type P2
// it will return false
Console.WriteLine(o1 is P2);
// checking whether o2
// is of type P2
// it will return false
Console.WriteLine(o2 is P2);
}
}
Output:
True
True
True
True
True
False
False
- as operator:
// C# program to illustrate the
// concept of 'as' operator
using System;
// Classes
class Y { }
class Z { }
class GFG {
// Main method
static void Main()
{
// creating and initializing object array
object[] o = new object[5];
o[0] = new Y();
o[1] = new Z();
o[2] = "Hello";
o[3] = 4759.0;
o[4] = null;
for (int q = 0; q < o.Length; ++q) {
// using as operator
string str1 = o[q] as string;
Console.Write("{0}:", q);
// checking for the result
if (str1 != null) {
Console.WriteLine("'" + str1 + "'");
}
else {
Console.WriteLine("Is is not a string");
}
}
}
}
Output:
0:Is is not a string
1:Is is not a string
2:'Hello'
3:Is is not a string
4:Is is not a string