C#中的is和as运算符
is运算符
有些类型之间的转换并不是能够转换成功,强制的转换反而会抛出一些异常,那么,可以使用is运算符来检查转换是否可以转换成功。is的语法如下:
variable is NewType
如果variable可以通过引用转换、装箱转换和拆箱转换的方式转换为NewType,那么运算符返回true。
举例如下:
class Animal
{
public string name = "动物";
public double weight = 30.00;
}
class Dog : Animal { }
class Cat : Animal { }
class Program
{
static void Main(string[] args)
{
double d1 = 48564.54;
int i1 = 88;
string s1 = "456";
Animal animal;
Dog dog = new Dog();
Cat cat = new Cat();
//检查dog是否可以转化为Animal类型
if (dog is Animal)
{
animal = dog;
Console.WriteLine("dog可以转化为Animal类型,Animal.name={0},Animal.weight={1}"
, animal.name, animal.weight);
}
Console.WriteLine(i1 is float);
Console.WriteLine(s1 is object);
Console.WriteLine(cat is Dog);
Console.ReadKey();
}
}
运行结果如下:
dog可以转化为Animal类型,Animal.name=动物,Animal.weight=30
False
True
False
as运算符
as和强制转换运算符比较类似,它不会抛出异常,如果转换失败,as运算符返回null。
需要注意的是as运算符只能用于引用转换和装箱转换,as不能用于值类型转换和用户自定义转换
举例如下:
class Animal
{
public string name = "动物";
public double weight = 30.00;
}
class Dog : Animal { }
class Cat : Animal { }
class Program
{
static void Main(string[] args)
{
double d1 = 48564.54;
int i1 = 88;
string s1 = "456";
Animal animal;
Dog dog = new Dog();
Cat cat = new Cat();
//检查dog是否可以转化为Animal类型
animal = dog as Animal;
if (animal != null)
Console.WriteLine("dog可以转化为Animal类型,Animal.name={0},Animal.weight={1}"
, animal.name, animal.weight);
object v1 = i1 as object; //装箱
int v2 = v1 as int; //拆箱 会报错
Console.WriteLine(v1);
Console.WriteLine(s1 as object);
Console.ReadKey();
}
}
这里v1 as int;会报错