c# 中 is和as 操作符是用来进行强制类型转换的
is : 检查一个对象是否兼容于其他指定的类型,并返回一个Bool值,永远不会抛出异常
object o = new object();
if (o is Label)
{
Label lb = (Label)o;
Response.Write("类型转换成功");
}
else
{
Response.Write("类型转换失败");
}
as:与强制类型转换是一样的,但是永远不会抛出异常,即如果转换不成功,会返回null
object o = new object();
Label lb = o as Label;
if (lb == null)
{
Response.Write("类型转换失败");
}
else
{
Response.Write("类型转换成功");
}
在做项目的时候,我们可以将is和as结合起来使用,由is负责把关检查,as负责转换类型
foreach (Control item in this.Controls)
{
if (item is Cards)
{
Cards card = item as Cards;
}
}