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
分配给 i
。 i
变成一个int
。在下一行中,i
被自动装箱到其相应的ReferenceType
(类),因此警告是显而易见的。我们甚至可以写
var b = i is int;
我希望这有助于澄清这个主题。
关于CIL指令 "isinst <valuetype>",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3551886/