C#“作为"演员阵容与经典演员阵容 [英] C# "as" cast vs classic cast

查看:18
本文介绍了C#“作为"演员阵容与经典演员阵容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
转换与在 CLR 中使用as"关键字

我最近了解了一种不同的投射方式.而不是使用

I recently learned about a different way to cast. Rather than using

SomeClass someObject = (SomeClass) obj;

可以使用以下语法:

SomeClass someObject = obj as SomeClass;

如果 obj 不是 SomeClass,它似乎返回 null,而不是抛出类转换异常.

which seems to return null if obj isn't a SomeClass, rather than throwing a class cast exception.

我发现如果转换失败并且我尝试访问 someObject 变量,这可能会导致 NullReferenceException.所以我想知道这种方法背后的基本原理是什么?为什么要使用这种转换方式而不是(旧的)转换方式 - 它似乎只是将失败转换的问题更深"地转移到代码中.

I see that this can lead to a NullReferenceException if the cast failed and I try to access the someObject variable. So I'm wondering what's the rationale behind this method? Why should one use this way of casting rather than the (old) one - it only seems to move the problem of a failed cast "deeper" into the code.

推荐答案

使用经典"方法,如果转换失败,InvalidCastException 被抛出.使用as方法,结果是null,可以检查,避免抛出异常.

With the "classic" method, if the cast fails, an InvalidCastException is thrown. With the as method, it results in null, which can be checked for, and avoid an exception being thrown.

此外,您只能将 as 与引用类型一起使用,因此如果您要强制转换为值类型,您仍然必须使用经典"方法.

Also, you can only use as with reference types, so if you are typecasting to a value type, you must still use the "classic" method.

注意:

as 方法只能用于可以分配 null 值的类型.过去仅表示引用类型,但当 .NET 2.0 出现时,它引入了可空值类型的概念.由于可以为这些类型分配一个 null 值,因此它们可以与 as 运算符一起使用.

The as method can only be used for types that can be assigned a null value. That use to only mean reference types, but when .NET 2.0 came out, it introduced the concept of a nullable value type. Since these types can be assigned a null value, they are valid to use with the as operator.

这篇关于C#“作为"演员阵容与经典演员阵容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆