gpt4 book ai didi

c# - 使用 'As' 而不是 () 进行转换?

转载 作者:行者123 更新时间:2023-11-30 13:33:12 25 4
gpt4 key购买 nike

我一直在阅读有关 SharePoint 2010 的工作,我注意到我从书籍到教学视频中遇到的许多代码示例都是以一种我从不知道 C# 中存在的方式转换为 SharePoint 对象(我认为是 VB 独有的) ):

SPWeb web = properties.Feature.Parent as SPWeb;

我已经习惯了以这种方式转换(在 VB 之外)(SPWeb)properties.Feature.Parent 并且很好奇我在 SharePoint 上遇到的大多数作品是否有任何特殊原因使用 VB 风格的转换符号。

最佳答案

as在 C# 中称为安全转换运算符。这与普通 Actor 之间存在语义差异。如果无法转换类型,则安全转换不会抛出异常;它将返回空值。如果无法转换类型,则普通转换会抛出 InvalidCastException

换句话说,如果 Parent if not of type SPWeb,则此代码分配 null:

SPWeb web = properties.Feature.Parent as SPWeb;

如果 Parent 的类型不正确,另一个版本会抛出异常:

SPWeb web = (SPWeb)properties.Feature.Parent;

as 运算符在您不确定是否可以将对象转换为所需类型时非常有用 - 在这种情况下,通常使用 as,然后检查是否为空。 as 仅适用于引用类型,因为值类型不能为 null。

this longer article on MSDN 中也对此进行了解释.

顺便说一下,VB 中的等效运算符是 TryCast(相对于 DirectCast)。

关于c# - 使用 'As' 而不是 (<T>) 进行转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9218965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com