问题描述
可能重复:
铸造VS使用'为'在CLR 关键字>
我看到铸件在C#中的两种不同的方式。
I have seen two different ways of casting in C#.
例如:
MyObj foo = (MyObj) bar; // this is what I see most of the times
MyObj foo = bar as MyObj; // I do see this sometimes
- 那么,什么是基本的区别是什么?
- 什么是正确的名称为
风格1
和风格2
铸造? - 如何决定什么时候使用什么?
- 是否有任何重大的性能问题?
- 还有什么我应该知道的有关这个主题?
- So, what is the basic difference?
- What are the proper names for the
style 1
andstyle 2
casting? - How do I decide when to use what?
- Is there any major performance issues?
- Is there anything else I should know of related to this topic?
非常感谢寻找到这一点:)
Thanks a lot for looking into this :)
推荐答案
第一个(直接或C风格中投)抛出一个异常,如果中投是无效的。它也是对对象执行实际类型转换的唯一途径。 (请注意,类型转换是从铸造不同,因为铸造只是更改的类型的变量的,而类型转换给你一个*不同类型的对象。)
The first one (a "direct" or "C-style" cast) throws an exception if the cast is invalid. It is also the only way to perform actual type conversion on the object. (Note that type conversion is different from casting, because casting merely changes the type of the variable, whereas type conversion gives you a *different type of object.)
第二个(没有特别的名字,虽然可以称之为试投,因为它被称为在VB.NET)的计算结果为空
的而不是抛出 InvalidCastException的
的。 (这种行为,因为它仅适用于引用类型)。
The second one (no particular name, although you can call it "try cast" as it's called in VB.NET) evaluates to null
instead of throwing an InvalidCastException
. (Because of this behavior it only works for reference types).
相比彼此无重大的性能问题。
No major performance issues compared to each other.
您使用为
只有当你的期望的,你的结果可能是无效的。否则,使用第一个。
You use as
only if you expect that your result might not be valid. Otherwise, use the first one.
另外, MSDN可能会有所帮助你的问题的一部分:
By the way, MSDN might be helpful for parts of your question:
在为
运营商就像是一个转换操作。但是,如果转换是不可能的,作为回报空
,而不是抛出一个异常。请看下面的EX pression:
expression as type
这是等效于下面的前pression除了EX pression只计算一次。
It is equivalent to the following expression except that expression is evaluated only one time.
expression is type ? (type)expression : (type)null
注意为
运算符只执行引用转换和装箱转换。该为
运营商无法执行其他转换,如用户定义的转换,而应改为使用浇铸前pressions进行。
Note that the as
operator only performs reference conversions and boxing conversions. The as
operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
这篇关于C#铸造不同的方式 - (T)VS OBJ OBJ为T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!