C#区别铸造和as? [英] C# difference between casting and as?
本文介绍了C#区别铸造和as?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
What is the difference between the following casts in c#?
之间的区别是什么?
在C#中,转换对象或使用作为
关键字有区别吗?希望这段代码会说明我的意思...
In C#, is a there difference between casting an object or using the as
keyword? Hopefully this code will illustrate what I mean...
String text = "Hello hello";
Object obj = text;
String originalCast = ((String)obj).ToUpper();
String originalAs = (obj as String).ToUpper();
感谢
:)
推荐答案
as
$ c> InvalidCastException 。相反,如果转换失败(它会给你一个 NullReferenceException
如果 obj
在你的示例中不是一个 string
)。
as
will never throw a InvalidCastException
. Instead, it returns null if the cast fails (which would give you a NullReferenceException
if obj
in your example were not a string
).
这篇关于C#区别铸造和as?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文