php的关键字as在什么结构中,运算符关键字as的使用

运算符关键字as的使用

引导语:运算符用于执行程序代码运算,会针对一个以上操作数项目来进行运算。以下是小编整理的运算符关键字as的使用,欢迎参考阅读!

as 运算符用于在兼容的'引用类型之间执行某些类型的转换。例如:

C#

class csrefKeywordsOperators

{

class Base

{

public override string ToString()

{

return "Base";

}

}

class Derived : Base

{ }

class Program

{

static void Main()

{

Derived d = new Derived();

Base b = d as Base;

if (b != null)

{

Console.WriteLine(b.ToString());

}

}

}

}

备注

as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而非引发异常。请看下面的表达式:

expression as type

它等效于以下表达式,但只计算一次 expression。

expression is type ? (type)expression : (type)null

注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用强制转换表达式来执行。

示例

C#

class ClassA { }

class ClassB { }

class MainClass

{

static void Main()

{

object[] objArray = new object[6];

objArray[0] = new ClassA();

objArray[1] = new ClassB();

objArray[2] = "hello";

objArray[3] = 123;

objArray[4] = 123.4;

objArray[5] = null;

for (int i = 0; i < objArray.Length; ++i)

{

string s = objArray[i] as string;

Console.Write("{0}:", i);

if (s != null)

{

Console.WriteLine("'" + s + "'");

}

else

{

Console.WriteLine("not a string");

}

}

}

}

/*

Output:

0:not a string

1:not a string

2:'hello'

3:not a string

4:not a string

5:not a string

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值