.NET - 如何使用“as”进行显式强制转换(内部)与 (someType)someobject 不同,为什么?
据我所知,当您使用这样的显式强制转换时:
(someType)someobject
如果 someobject
不是真正的 someType
,您可能会收到无效的强制转换异常。
我也明白,当您像这样使用 as
进行转换时:
myObject = someObject as someType
如果 someObject
不是',则 myObject
只是呈现 null
确实是someType
。
这些评估有何不同,为什么?
I understand that when you use an explicit cast like this:
(someType)someobject
you can get an invalid cast exception if someobject
is not really someType
.
As well I understand that when you cast with as
like this:
myObject = someObject as someType
myObject
is just rendered null
if someObject
isn't really someType
.
How are these evaluated differently and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
John Skeet 有一个 C# 常见问题解答,其中解释了两个运算符之间的差异。请参阅“使用强制转换语法和
as
运算符之间有什么区别?”段落。引用 :
John Skeet has a C# faq where he explains the differences between the two operators. See paragraph 'What's the difference between using cast syntax and the
as
operator?'.Quote :
几年过去了......但几分钟前我遇到了一个我认为值得注意的实际例子 - 两者之间的区别:
检查一下:
底线: GenericCaster2 不适用于结构类型。 GenericCaster 会的。
Years have passed... but minutes ago I came across a practical example I think is worth noting - of the difference between the two:
Check this out:
Bottom line: GenericCaster2 will not work with struct types. GenericCaster will.