C# 中的 IS 与 AS 运算符
csharpprogrammingserver side programming更新于 2025/7/13 0:37:17
IS 运算符
C# 中的"is"运算符用于检查对象的运行时类型是否与给定类型兼容。
以下是语法 −
expr 是类型
这里,expr 是表达式
type 是类型的名称
以下是 C# 中 is 运算符用法的示例
示例
using System;
class One { }
class Two { }
public class Demo {
public static void Test(object obj) {
One x;
Two y;
if (obj is One) {
Console.WriteLine("Class One");
x = (One)obj;
} else if (obj is Two) {
Console.WriteLine("Class Two");
y = (Two)obj;
} else {
Console.WriteLine("None of the classes!");
}
}
public static void Main() {
One o1 = new One();
Two t1 = new Two();
Test(o1);
Test(t1);
Test("str");
Console.ReadKey();
}
}
输出
Class One Class Two None of the classes!
AS 运算符
"as"运算符用于在兼容类型之间执行转换。它类似于强制类型转换,并且仅执行引用转换、可空转换和装箱转换。as 运算符无法执行其他转换,例如用户定义的转换,这些转换应使用强制类型转换表达式来执行。
以下示例展示了 C# 中 as 运算符的用法。此处 as 用于转换 −
string s = obj[i] as string;
尝试运行以下代码,在 C# 中使用 ‘as’ 运算符−
示例
using System;
public class Demo {
public static void Main() {
object[] obj = new object[2];
obj[0] = "jack";
obj[1] = 32;
for (int i = 0; i < obj.Length; ++i) {
string s = obj[i] as string;
Console.Write("{0}: ", i);
if (s != null)
Console.WriteLine("'" + s + "'");
else
Console.WriteLine("This is not a string!");
}
Console.ReadKey();
}
}
输出
0: 'jack' 1: This is not a string!

