8

我正在编写一个 IL 静态分析工具,但我很难理解管理如何引用泛型类型参数的规则:

取这个 IL(来自IList<T>界面):

.property instance !T Item(
    int32 index
)
{
    .get instance !0 System.Collections.Generic.IList`1::get_Item(int32)
    .set instance void System.Collections.Generic.IList`1::set_Item(int32, !0)
}

为什么是!0there 而不是!T?我认为就虚拟机而言它们是等效的,当您保证拥有名称时,使用位置引用似乎很奇怪。

更新:另一个案例,来自 KeyedCollection.ctor:

IL_0037:  newobj instance void class System.Collections.Generic.Dictionary`2<!TKey,!TItem>::'.ctor'(class System.Collections.Generic.IEqualityComparer`1<!0>)
IL_003c:  stfld class System.Collections.Generic.Dictionary`2<!0,!1> class System.Collections.ObjectModel.KeyedCollection`2<!0,!1>::dictionary
4

1 回答 1

4

In the Common Language Infrastructure standard, Partition II - Metadata and File Format, clause 7.1 "Types" it states:

Type ::=        Description
--------        -----------
'!'             Generic parameter in a type definition, accessed by index from 0

So short answer: because it's in the spec.

Long answer: This is speculation on my part, but basically, most IL commands are stack-based and use positional references as parameters all the time. That said, it makes sense that positional references are used for generics, in order to maintain common patterns/usage mechanisms in IL.

于 2012-07-13T18:49:00.143 回答