is运算符
1、is
运算符检查表达式结果的运行时类型是否与给定类型兼容。
2、is
运算符还会对照某个模式测试表达式结果。
写法
E is T
其中 E
是返回一个值的表达式,T
是类型或类型参数的名称。 E
不得为匿名方法或 Lambda 表达式。
如果表达式结果为非 null 并且满足以下任一条件,则 is
运算符将返回 true
:
1、表达式结果的运行时类型为 T
。
示例代码如下所示:
internal class Program
{
public class Base { }
public class Derived : Base { }
static void Main(string[] args)
{
object b = new Base();
Console.WriteLine(b is Base); // output: True
Console.WriteLine(b is Derived); // output: False
}
}
输出的结果如下图所示:
查看如下代码:
object b = new Base();
Console.WriteLine(b is Base); // output: True
虽然在编译期看过去b是object类型,但是在运行时b的类型为Base(),因此b is Base返回True,
而b运行时类型不为Derived,且也不派生自Derived,因此b is Derived返回False。
查看b的类型,使用getType方法,代码如下所示:
internal class Program
{
public class Base { }
public class Derived : Base { }
static void Main(string[] args)
{
object b = new Base();
Console.WriteLine(b is Base); // output: True
Console.WriteLine(b.GetType());
Console.WriteLine(b is Derived); // output: False
}
}
运行结果如下图所示:
2、表达式结果的运行时类型派生自类型 T
、实现接口 T
,或者存在从其到 T
的另一种隐式引用转换
检查派生关系示例代码如下所示:
internal class Program
{
public class Base { }
public class Derived : Base { }
static void Main(string[] args)
{
object d = new Derived();
Console.WriteLine(d is Base); // output: True
Console.WriteLine(d.GetType());
Console.WriteLine(d is Derived); // output: True
}
}
运行结果如下图所示:
可知d的运行时类型为Derived,因此d is Derived结果为True,而Derived派生自Base,因此d is Base结果为True。
检查接口实现示例代码如下所示:
internal class Program
{
interface IDrawable
{
void Draw();
}
class Circle : IDrawable
{
public void Draw()
{
// 实现接口的方法
}
}
static void Main(string[] args)
{
Circle circle = new Circle();
Console.WriteLine(circle is IDrawable); // true,因为 Circle 实现了 IDrawable 接口
}
}
3、表达式结果的运行时类型是基础类型为 T
且 Nullable.HasValue 为 true
的可为空值类型。
示例代码如下所示:
internal class Program
{
static void Main(string[] args)
{
int? nullableInt = 42; // 创建一个可为空的整数类型
Console.WriteLine(nullableInt is int?); // true,因为 nullableInt 是 int? 类型,且有值
}
}
运行结果如下图所示:
将代码改写如下:
internal class Program
{
static void Main(string[] args)
{
int? nullableInt = null; // 创建一个可为空的整数类型
Console.WriteLine(nullableInt is int?); // false,因为 nullableInt 是 int? 类型,但是为null
}
}
运行结果如下所示:
4、存在从表达式结果的运行时类型到类型 T
的装箱或取消装箱转换。
示例代码如下:
internal class Program
{
static void Main(string[] args)
{
int i = 27;
Console.WriteLine(i is System.IFormattable); // output: True
object iBoxed = i;
Console.WriteLine(iBoxed is int); // output: True
Console.WriteLine(iBoxed is long); // output: False
}
}
运行结果如下所示:
is
运算符还会对照某个模式测试表达式结果。
示例代码如下:
internal class Program
{
static void Main(string[] args)
{
int i = 25;
object iBoxed = i;
int? jNullable = 3;
if (iBoxed is int a && jNullable is int b)
{
Console.WriteLine(a + b); // output 28
}
}
}
运行结果如下图所示: