【发布时间】:2017-07-30 05:40:56
【问题描述】:
在下面的代码中,两个对象的类型对象指针都指向整数类型列表。
IEnumerable<int> list1 = new List<int>();
List<int> list2 = new List<int>();
在哪里声明了 list1 的类型(IEnumerable),存储在运行时?
【问题讨论】:
在下面的代码中,两个对象的类型对象指针都指向整数类型列表。
IEnumerable<int> list1 = new List<int>();
List<int> list2 = new List<int>();
在哪里声明了 list1 的类型(IEnumerable),存储在运行时?
【问题讨论】:
不确定它是否回答了您的问题,但它存储在 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
但这并不完全是“运行时”。在运行时,JIT 很可能会将其转换为原始指针操作,因此您的答案可能是“无处”。或者,因为编译器在编译时知道变量的类型很重要,所以答案是“在你的源代码中”。
【讨论】:
list1和list2中的指针不同,它们已经指向不同对象的不同接口。无需进一步区分。