is运算符检查未知的变量(该变量可能用作对象参数,传递给一个方法)是否可以转换为给定的类型。
注:is运算符不会检查两个类型是否相同,但可以检查他们是否兼容。
语法方式:
<operand> is <type>
表达式结果为一个bool量,根据以下情况来确定值:
如果type是一个类,operand也是该类型,或者是继承了该类型,或者是被封装到该类型中,返回true
如果type是一个接口,operand是该类型,或者是继承了该类型,或者是执行该接口的类型,返回true
如果type是一个值类型,operand是该类型,或者是他能被折装到该类型中,返回true
以下是一个范例:
using System;
namespace Ch11Ex03
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
///
class Checker
{
public void Check(object param1)
{
if(param1 is ClassA)
Console.WriteLine("Variable can be converted to ClassA");
else
Console.WriteLine("Variable can not be converted to ClassA");
if(param1 is IMyInterface)
Console.WriteLine("Variable can be converted to IMyInterface");
else
Console.WriteLine("Variable can not be converted to IMyInterface");
if(param1 is MyStruct)
Console.WriteLine("Variable can be converted to MyStruct");
else
Console.WriteLine("Variable can not be converted to MyStruct");
}
}
interface IMyInterface
{
}
class ClassA:IMyInterface
{
}
class ClassB:IMyInterface
{
}
class ClassC
{
}
class ClassD:ClassA
{
}
struct MyStruct:IMyInterface
{
}
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Checker check=new Checker();
ClassA try1=new ClassA();
ClassB try2=new ClassB();
ClassC try3=new ClassC();
ClassD try4=new ClassD();
MyStruct try5=new MyStruct();
object try6=try5;
Console.WriteLine("Analyzing ClassA type variable");
check.Check(try1);
Console.WriteLine("/nAnalyzing ClassB type variable");
check.Check(try2);
Console.WriteLine("/nAnalyzing ClassC type variable");
check.Check(try3);
Console.WriteLine("/nAnalyzing ClassD type variable");
check.Check(try4);
Console.WriteLine("/nAnaylyzing MyStruct type variable");
check.Check(try5);
Console.WriteLine("/nAnaylyzing boxed MyStruct type variable");
check.Check(try6);
}
}
}
输出结果:
Analyzing ClassA type variable
Variable can be converted to ClassA //本身就是该类型
Variable can be converted to IMyInterface //实现了IMyInterface接口
Variable can not be converted to MyStruct
Analyzing ClassB type variable
Variable can not be converted to ClassA
Variable can be converted to IMyInterface
Variable can not be converted to MyStruct
Analyzing ClassC type variable
Variable can not be converted to ClassA //单独是一个类型,不能转换为任何其他的类型
Variable can not be converted to IMyInterface
Variable can not be converted to MyStruct
Analyzing ClassD type variable
Variable can be converted to ClassA //继承了A类,可以兼容转换
Variable can be converted to IMyInterface //继承了A类,所以间接实现了IMyInterface接口
Variable can not be converted to MyStruct
Anaylyzing MyStruct type variable
Variable can not be converted to ClassA
Variable can be converted to IMyInterface //结构实现了IMyInterface接口
Variable can be converted to MyStruct
Anaylyzing boxed MyStruct type variable
Variable can not be converted to ClassA
Variable can be converted to IMyInterface
Variable can be converted to MyStruct // 程序中的object封箱了MyStruct值类型,所以可以转换
结果分析,在注释中
类型的转换判断