强制转换和 as 之间的 C# 区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/955250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# difference between casting and as?
提问by
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...
在 C# 中,转换对象或使用as
关键字有区别吗?希望这段代码能说明我的意思......
String text = "Hello hello";
Object obj = text;
String originalCast = ((String)obj).ToUpper();
String originalAs = (obj as String).ToUpper();
Thanks
谢谢
:)
:)
采纳答案by Matthew Flaschen
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
).
as
永远不会抛出InvalidCastException
. 相反,如果转换失败,它会返回 null (这会给你一个NullReferenceException
ifobj
在你的例子中不是 a string
)。
回答by Paul Mitchell
Using 'as' will not throw an exception if the obj is not a String. Instead it'll return null. Which in your case will still throw an exception since you're immediately referencing this null value.
如果 obj 不是字符串,则使用 'as' 不会引发异常。相反,它会返回 null。在您的情况下,由于您立即引用此空值,因此仍会引发异常。
回答by Lewis
As far as I know!
据我所知!
Using 'as' will return null if the 'cast' fails where casting will throw an exception if the cast fails.
如果 'cast' 失败,则使用 'as' 将返回 null,如果转换失败,则转换将抛出异常。
回答by Mehrdad Afshari
Other than InvalidCastException
that's already mentioned...
除了InvalidCastException
已经提到的...
as
will not work if the target type is a value type (unless it's nullable):
as
如果目标类型是值类型,则不起作用(除非它可以为 null):
obj as int // compile time error.