CIL指令 "isinst <valuetype>"

标签 cil

ECMA 公共(public)语言基础设施文档对 CIL“isinst class”指令有这样的描述:

Correct CIL ensures that class is a valid typeref or typedef or typespec token indicating a class, and that obj is always either null or an object reference.

这意味着不允许使用值类型,对吗?但 mscorlib.dll 包含一个 System.RuntimeTypeHandle::Equals(object obj) 方法,其指令如下:

IL_0001: isinst System.RuntimeTypeHandle

而 System.RuntimeTypeHandle 是一个值类型。有人可以把我放在这里吗?

最佳答案

看看RuntimeTypeHandle的声明:

.class public sequential ansi serializable sealed beforefieldinit RuntimeTypeHandle
    extends     System.ValueType
    implements  System.Runtime.Serialization.ISerializable

虽然RuntimeTypeHandle被声明为一个结构,但它在CIL中的表示是某种特殊的类。换句话说,您可以将结构想象为继承自 System.ValueType 且其属性遵循严格顺序的特殊类。

考虑到这一点,isinst 可以通过 RuntimeTypeHandle 进行调用。对于我的解释,isinst 根本不限于引用类型,只要有一个代表该类型的类即可。

假设我们用 C# 编写:

var i = 4;
var b = i is Int32;

我们收到编译器警告

Warning: The given expression is always of the provided ('int') type.

会发生什么?我们将 4 分配给 ii变成一个int。在下一行中,i被自动装箱到其相应的ReferenceType(类),因此警告是显而易见的。我们甚至可以写

var b = i is int;

我希望这有助于澄清这个主题。

关于CIL指令 "isinst <valuetype>",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3551886/

相关文章:

.net - 这些 CIL 语句之间有什么区别?

.NET CIL 调用还是 CallVirt?

c# - OnExit 不是通过 PostSharp 进入 asp.net 项目

.net - 是否有通用 CIL 代码将任何类型实例转换为字符串?

.net - 有没有办法将 C++ 代码编译为 Microsoft .Net CIL(字节码)?

c# - 处理双 NaN 和 Inf 时的 ILASM 问题

.net - MSIL 虚拟地址

c# - 有没有工具可以在 Visual Studio 中选择一些代码并让它显示相应的 MSIL?

c# - 如何使用 .net cil jmp 操作码

c# - LINQ是如何编译成CIL的?