当我将变量声明为接口,然后为其指定具体类型时,保存的声明类型在哪里?

时间:2017-03-09 09:49:08

标签: c# .net types interface

在下面的代码中,两个对象的类型对象指针指向整数类型List。

IEnumerable<int> list1 = new List<int>();
List<int> list2 = new List<int>();

list1声明的类型(IEnumerable)在哪里存储在运行时?

1 个答案:

答案 0 :(得分:0)

不确定它是否回答了您的问题,但它存储在IL的.locals部分。

.maxstack 1
.entrypoint
.locals init (
    [0] class [mscorlib]System.Collections.Generic.IEnumerable`1<int32> list1,
    [1] class [mscorlib]System.Collections.Generic.List`1<int32> list2
)

IL_0000: nop
IL_0001: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_0006: stloc.0
IL_0007: newobj instance void class [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
IL_000c: stloc.1
IL_000d: ret

这不完全是&#34;运行时&#34;虽然。在运行时,JIT很可能将其转换为原始指针操作,因此您的答案可能是“无处不在”#34;。或者,因为编译器在编译时知道变量的类型是唯一重要的,所以答案是#34;在源代码中#34;。