c# - .NET - 使用 "as"显式转换与 (someType)someobject 有何不同(在内部),为什么?

标签 c# .net casting explicit

我理解当您使用这样的显式强制转换时:

(someType)someobject

如果 someobject 不是真正的 someType,您可能会得到一个无效的转换异常。

据我所知,当您像这样使用 as 进行转换时:

myObject = someObject as someType
如果 someObject 不是真正的 someType

myObject 将被呈现为 null

如何对这些进行不同的评估,为什么?

最佳答案

John Skeet 有一个 C# faq他解释了两个运营商之间的差异。请参阅“使用强制转换语法和 as 运算符有什么区别?”段落。

引用:

Using the as operator differs from a cast in C# in three important ways:

  1. It returns null when the variable you are trying to convert is not of the requested type or in its inheritance chain, instead of throwing an exception.
  2. It can only be applied to reference type variables converting to reference types.
  3. Using as will not perform user-defined conversions, such as implicit or explicit conversion operators, which casting syntax will do.

There are in fact two completely different operations defined in IL that handle these two keywords (the castclass and isinst instructions) - it's not just "syntactic sugar" written by C# to get this different behavior. The as operator appears to be slightly faster in v1.0 and v1.1 of Microsoft's CLR compared to casting (even in cases where there are no invalid casts which would severely lower casting's performance due to exceptions).

关于c# - .NET - 使用 "as"显式转换与 (someType)someobject 有何不同(在内部),为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063535/

相关文章:

c# - 为 Oracle 返回一个记录集作为 HTML

c# - 用于检查给定密码是否至少包含一个数字和一个字母的正则表达式?

java - 在 Play Framework 中将字符串转换为 Html

sqlite - Dart-使用泛型将List <SuperType>转换为List <SubType>

c# - 如何使用 ORMlite 将 byte[] 数组插入图像列

c# - 如何更新已从 BOT 发送给用户的自适应卡?

c# - 如何从 HttpContext.Current.Request 获取 URL 的 # 部分

C# 泛型强制转换

c# - 如何在 WSDL 中定义一组自定义类型?

C# Page_Load 中的 javascript 函数