Casting: (NewType) vs. Object as NewType [duplicat

2019-01-02 15:11发布

Possible Duplicate:
Casting vs using the 'as' keyword in the CLR

What is actually the difference between these two casts?

SomeClass sc = (SomeClass)SomeObject;
SomeClass sc2 = SomeObject as SomeClass;

Normally, they should both be explicit casts to the specified type?

标签: c# .net
12条回答
素衣白纱
2楼-- · 2019-01-02 15:57

It's like the difference between Parse and TryParse. You use TryParse when you expect it might fail, but when you have strong assurance it won't fail you use Parse.

查看更多
荒废的爱情
3楼-- · 2019-01-02 15:59

To expand on Rytmis's comment, you can't use the as keyword for structs (Value Types), as they have no null value.

查看更多
高级女魔头
4楼-- · 2019-01-02 16:02

Well the 'as' operator "helps" you bury your problem way lower because when it is provided an incompatible instance it will return null, maybe you'll pass that to a method which will pass it to another and so on and finally you'll get a NullReferenceException which will make your debugging harder.

Don't abuse it. The direct cast operator is better in 99% of the cases.

查看更多
只靠听说
5楼-- · 2019-01-02 16:07

A difference between the two approaches is that the the first ((SomeClass)obj) may cause a type converter to be called.

查看更多
浅入江南
6楼-- · 2019-01-02 16:07

For those of you with VB.NET experience, (type) is the same as DirectCast and "as type" is the same as TryCast.

查看更多
君临天下
7楼-- · 2019-01-02 16:08

All of this applies to reference types, value types cannot use the as keyword as they cannot be null.

//if I know that SomeObject is an instance of SomeClass
SomeClass sc = (SomeClass) someObject;


//if SomeObject *might* be SomeClass
SomeClass sc2 = someObject as SomeClass;

The cast syntax is quicker, but only when successful, it's much slower to fail.

Best practice is to use as when you don't know the type:

//we need to know what someObject is
SomeClass sc;
SomeOtherClass soc;

//use as to find the right type
if( ( sc = someObject as SomeClass ) != null ) 
{
    //do something with sc
}
else if ( ( soc = someObject as SomeOtherClass ) != null ) 
{
    //do something with soc
}

However if you are absolutely sure that someObject is an instance of SomeClass then use cast.

In .Net 2 or above generics mean that you very rarely need to have an un-typed instance of a reference class, so the latter is less often used.

查看更多
登录 后发表回答