是什么铸造并使用&QUOT之间的差;如"在C#中? [英] What is the difference between casting and using "as" in C#?
本文介绍了是什么铸造并使用&QUOT之间的差;如"在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果是有区别的,就是做以下投的两种方法之间的区别?
在这种情况下,电子
是 GridViewRowEventArgs
对象。
的GridView GV =(GridView控件)e.Row.FindControl(货车); //第一种方式GridView控件GV2 = e.Row.FindControl(GV)作为GridView控件; //第二种方法
解决方案
的区别是:
- 如果一个转换失败,它抛出一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx\"><$c$c>InvalidCastException$c$c>.
- 如果在
为
运营商失败,它只是返回一个空引用。 - 您不能使用
为
与非空值类型(例如,你不能这样做0为int
)。 - 转换操作符也用于拆箱。 (
为
可用于拆箱到一个空值类型。) - 转换操作符还可以执行用户定义的转换。
编辑:我的written什么时候,我觉得在其他地方合适的做法是使用哪个运营商。这可能是值得一读...
If there is a difference, what is the difference between the two ways of doing the following cast?
In this case e
is a GridViewRowEventArgs
object.
GridView gv = (GridView)e.Row.FindControl("gv"); //first way
GridView gv2 = e.Row.FindControl("gv") as GridView; //second way
解决方案
The differences are:
- If a cast fails, it throws an
InvalidCastException
. - If the
as
operator fails, it just returns a null reference. - You can't use
as
with non-nullable value types (e.g. you can't do "o as int
"). - The cast operator is also used for unboxing. (
as
can be used to unbox to a nullable value type.) - The cast operator can also perform user-defined conversions.
EDIT: I've written elsewhere about when I feel it's appropriate to use which operator. That might be worth a read...
这篇关于是什么铸造并使用&QUOT之间的差;如&QUOT;在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文