开发者

C#: Is there any Difference between (Type)Something vs Something as Type [duplicate]

开发者 https://www.devze.com 2023-01-19 05:03 出处:网络
This qu开发者_如何学Goestion already has answers here: Closed 12 years ago. Possible Duplicate: Direct casting vs 'as' operator?
This qu开发者_如何学Goestion already has answers here: Closed 12 years ago.

Possible Duplicate:

Direct casting vs 'as' operator?

Casting vs. using the as keyword in the CLR

In C#, whats the difference

var obj = (Array)Something

vs

var obj = Something as Array


first will throw a CastException if invalid. The second will only result in obj = null instead.


As well as Danijels answers

The first can be used with any type.

The as operator can only be used on reference types.


var obj = (Array)Something 

will throw an InvalidCastExcpetion if Something not derived from System.Array or does not have a conversion operator for System.Array. This can be used with value types and reference types.

var obj = Something as Array

will return null (obj will be null) if Something not derived from System.Array or does not have a conversion operator for System.Array. This can be used only with reference types. You'd need to box you value type first.

0

精彩评论

暂无评论...
验证码 换一张
取 消