开发者

object casting in C# [duplicate]

This question already has answers here: 开发者_Python百科 Closed 12 years ago.

Possible Duplicate:

Casting: (NewType) vs. Object as NewType

Just wanted to know which one is faster and what's the difference.

MyClass test = someclass as MyClass;

or

MyClass test = (MyClass)someclass;


The difference is that the as keyword does not throw an exception when it fails and instead it fills the l-value with null whereas casting with brackets will throw an InvalidCastException.


The as keyword will return null if the desired cast is not valid. Explicit casting will throw an exception in that case. Consequently, I believe the implicit cast (as) is slower, though it's likely negligible.


Faster? It probably isn't going to ever matter. You'll have to wait until there is a scenario where your performance profiling application tells you to that the cast is taking too long.

Difference?

Will set test to null when someclass can't be cast to MyClass.

MyClass test = someclass as MyClass; 

Will throw an exception when someclass can't be cast to MyClass.

MyClass test = (MyClass)someclass;


as casting is faster than prefix casting, but doesn't produce reliable results, ie. it returns null if the cast can't be executed. You'll have to deal with that yourself. Prefix casting will throw an exception if T1 can't be casted to T2.

See: blog

object casting in C# [duplicate]

See codeproject

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜